一、模块化
1、几个组件定义几个对象
文件 src/store/index.js
// 与count组件相关的optinos const countOptions = {actions:{},mutations:{},state:{},getters:{} } // 与person组件 相关的options const personOptions = {actions:{},mutations:{},state:{},getters:{} }
2、把之前相关联的内容填充,注意每个对象都要加 namespaced: true,
// 与count组件相关的optinos const countOptions = {
namespaced: true,actions:{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){// console.log(state.sum, value)state.sum += value},SUB(state, value){state.sum -= value},},state:{sum:0,name: "jojo",},getters:{bigSum(state){return state.sum * 10}} } // 与person组件 相关的options const personOptions = {
namespaced: true,actions:{},mutations:{ADD_PERSON(state, value){state.personLst.unshift(value)},},state:{personLst:[{id:"001", name:"张三"}]},getters:{} }
3、修改暴露 使用 modules
export default new Vuex.Store({modules:{countOptions,personOptions} })
二、使用
1、mapState和mapGetters 想要正常使用需要添加 定义的对象
computed:{...mapState('countOptions' ,['name', 'sum']),...mapState('personOptions', ["personLst"]),...mapGetters('countOptions',["bigSum"]) }
2、mapActions和mapMutations 想要正常使用,需添加index.js中定义的对象
methods:{...mapActions('countOptions',{addNumOdd:"addOdd", addNumWait:"addWait"}),...mapMutations('countOptions',{addNum:"ADD", subisNum:"SUB"}), }