03提纲
简单的充值系统、模块化router、优化store
github地址:github.com/Yado-yu/yad…
简单的充值
1、在src/store/modules/dormitory.vue中,代码如下:
export default {
namespaced: true,
state:{
currentDorm:null,
dormList:[
{
dormId:'330',
dormBoss:'student03',
dormPerson:'student03,student04',
light:20,
kongtiao:20,
water:20,
isGood:'yes',
},
{
dormId:'331',
dormBoss:'yado',
dormPerson:'yado,student05',
light:10,
kongtiao:10,
water:10,
isGood:'yes'
},
{
dormId:'332',
dormBoss:'student06',
dormPerson:'student06,student07',
light:30,
kongtiao:30,
water:30,
isGood:'yes'
},
{
dormId:'333',
dormBoss:'student08',
dormPerson:'student08,student09',
light:40,
kongtiao:40,
water:40,
isGood:'yes'
},
]
},
actions:{
pay({state , commit},{ payWay, payDorm , payNum }){
console.log(payWay, payDorm , payNum);
state.currentDorm = state.dormList.find(dorm=> dorm.dormId === payDorm)
console.log(state.currentDorm);
commit('PAY',{ payWay , payNum })
}
},
mutations:{
PAY({currentDorm},{ payWay , payNum }){
switch (payWay) {
case 'Light':
currentDorm.light += payNum
break;
case 'Kongtiao':
currentDorm.kongtiao += payNum
break;
case 'Water':
currentDorm.water += payNum
break;
default:
break;
}
}
}
}
2、在src/pages/Light.vue中,代码如下:
<template>
<el-form :inline="true" class="demo-form-inline">
<el-form-item label="照明充值宿舍">
<el-select v-model="value" placeholder="请选择">
<el-option
v-for="item in dormList"
:key="item.dormId"
:label="item.dormId"
:value="item.dormId">
</el-option>
</el-select>
</el-form-item>
<el-form-item label="充值金额">
<el-input v-model.number="money" placeholder="充值金额"></el-input>
</el-form-item>
<el-form-item>
<el-button type="primary" @click="onSubmit">充值</el-button>
</el-form-item>
</el-form>
</template>
<script>
import { mapState , mapActions } from 'vuex'
export default {
data() {
return {
value: '',
money:'',
}
},
methods: {
onSubmit() {
this.$confirm(`确定给宿舍${this.value}充值照明电费${this.money}元`, '提示', {
confirmButtonText: '确定',
cancelButtonText: '取消',
type: 'warning'
}).then(() => {
//提交充值信息
this.pay({
payWay:'Light',
payDorm:this.value,
payNum:this.money
})
this.$message({
type: 'success',
message: '充值成功!'
});
}).catch(() => {
this.$message({
type: 'info',
message: '已取消充值'
});
});
},
...mapActions('dormitorys',['pay'])
},
computed:{
...mapState('dormitorys',['dormList'])
},
created() {
console.log(this.$route)
}
}
</script>
<style scoped>
::v-deep .el-form-item__label {
color: #000;
}
</style>
空调、水费同理
模块化router
1、index.js中
export const arrRoutes = [{
path:'home',
name: 'home',
component:Home,
meta: {
title: '首页',
icon: 'el-icon-s-home'
}
},].concat(lookDorm,pay,fix,person)
优化store
在index.js中
//遍历当前文件夹modules下的所有文件,选出以'.js'结尾的文件, false表示不会深层遍历
const modules = require.context('./modules/', false, /\.js$/)
console.log(modules, modules.prototype)
const MOD = {}
modules.keys().forEach(key => {
//得到文件名
const name = key.replace(/\.\/(\w+?)\.js$/, '$1')
//将默认暴露内容赋给MOD[name]
MOD[name] = modules(key).default
});
console.log('###',MOD)
export default new Vuex.Store({
...
modules: MOD,
})
这样新增模块不再需要手动引入