Vuex的模块化编码
一般配合命名空间一起使用
-
目的:方便代码维护,让多种数据分类明确
-
修改store中的index.js文件
// 求和功能相关配置 const countOptions = { namespaced:true, actions: { add(context, value) { // contest 上下文对象 context.commit('ADD', value) }, minus(context, value) { context.commit('MINUS', value) }, addOdd(context, value) { if (context.state.sum % 2) { context.commit('ADD', value) } }, addWait(context, value) { setTimeout(() => { context.commit('ADD', value) }, 500) } }, mutations: { ADD(state, value) { state.sum += value }, MINUS(state, value) { state.sum -= value }, }, state: { sum: 0, school: '测试', subject: '前端', }, getters: { bigSum(state) { return state.sum * 10 } } } impor// 人员管理相关配置 import axios from "axios"; import {nanoid} from "nanoid"; const personOptions = { // 命名空间 namespaced:true, actions: { addPersonWang(context,value){ if (value.name.indexOf('王')===0){ context.commit('ADDPERSON',value) }else { alert('添加的人必须姓王') } }, addPersonServe(context){ axios.get('https://v.api.aa1.cn/api/yiyan/index.php').then( response=>{ console.log(response.data) context.commit('ADDPERSON',{id:nanoid(),name:response.data}) }, error=>{ error.message } ) } }, mutations: { ADDPERSON(state, value) { state.personList.unshift(value) } }, state: { personList: [ {id: '001', name: '张三'} ] }, getters: { firstPersonName(state){ return state.personList[0].name } } } export default new Vuex.Store({ modules:{ countOptions, personOptions } })
-
开启命名空间后,组件中读取数据
-
读取state中数据
-
自己直接读取
-
借助mapState读取
personList(){ return this.$store.state.personOptions.personList }, sum(){ return this.$store.state.countOptions.sum }, ...mapState('countOptions',['sum', 'school', 'subject']), ...mapState('personOptions',['personList']),
-
-
读取getters中数据
-
自己直接读取
-
借助mapGetters读取
firstPersonName(){ return this.$store.getters["personOptions/firstPersonName"] } ...mapGetters('countOptions',['bigSum']),
-
-
组件中调用dispatch
-
自己直接读取
-
借助mapActions读取
addWang(){ const personObj={id:nanoid(),name:this.name} this.$store.dispatch('personOptions/addPersonWang',personObj) this.name='' }, addPersonServer(){ this.$store.dispatch('personOptions/addPersonServe') } ...mapActions('countOptions',{incrementOdd:'addOdd',incrementWait:'addWait'})
-
-
组件中调用commit
-
自己直接读取
-
借助mapMutations读取
add(){ const personObj={id:nanoid(),name:this.name} this.$store.commit('personOptions/ADDPERSON',personObj) this.name='' }, ...mapMutations('countOptions',{increment:'ADD',decrement:'MINUS'}),
-
-