Vuex namespaced
Vuex namespaced
namespaced: 用于划分不同模块的状态
案例
store/index.js
import Vue from 'vue'
import Vuex from 'vuex'
// 注册Vuex插件
Vue.use(Vuex)
const CounterOptions = {
namespaced: true,
// 修改数据的动作
actions: {
INCRE_ODD(context, payload) {
context.state.count % 2 !== 0 && context.dispatch('INCRE_ASYNC', payload)
},
INCRE_ASYNC(context, payload) {
setTimeout(() => {
context.commit('incre', payload)
}, 500);
},
DECRE_ASYNC(context, payload) {
setTimeout(() => {
context.commit('decre', payload)
}, 500);
}
},
// 操作数据的行为
mutations: {
incre(state, payload) {
state.count += payload
},
decre(state, payload) {
state.count -= payload
}
},
// 初始化数据
state: {
count: 0,
prop1: 'prop1 value',
prop2: 'prop2 value'
},
getters: {
bigCount(state) {
return state.count * 10
}
}
}
const PersonOptions = {
namespaced: true,
actions: {
CHANGE_NAME(context, payload) {
setTimeout(() => {
context.commit('changeName', payload)
}, 500);
}
},
mutations: {
changeName(state, payload) {
state.name += payload
}
},
state: {
name: 'island'
}
}
export default new Vuex.Store({
modules: {
CounterAbout: CounterOptions,
PersonAbout: PersonOptions
}
})
组件1 Counter.vue
<template>
<div>
<select v-model.number="unit">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<button @click="increment(unit)">加</button>
<button @click="decrement(unit)">减</button>
<button @click="increOdd(unit)">奇数加</button>
<button @click="decreAsync(unit)">异步减</button>
<h1>{{count}}</h1>
<h1>{{ bigCount }}</h1>
<PersonVue />
</div>
</template>
<script>
import { mapState, mapGetters, mapMutations, mapActions } from "vuex";
import PersonVue from './components/Person.vue';
export default {
data: () => ({ unit: 1 }),
computed:{
// 对象写法
// ...mapState('CounterAbout',{count:'count',prop1:'prop1',prop2:'prop2'}),
// ...mapGetters('CounterAbout',{bigCount:'bigCount'})
// 数组写法
...mapState('CounterAbout',['count','prop1','prop2']),
...mapGetters('CounterAbout',['bigCount'])
},
methods: {
...mapMutations('CounterAbout',{increment:'incre',decrement:'decre'}),
...mapActions('CounterAbout',{increOdd:'INCRE_ODD',decreAsync:'DECRE_ASYNC'})
},
components:{PersonVue}
};
</script>
组件2 Person.vue
<template>
<div>
<hr />
上方组件的count是:
<h1>{{ count }}</h1>
<h1>名字:{{ name }}</h1>
<button @click="changeName">名字+1</button>
</div>
</template>
<script>
import { mapState } from "vuex";
export default {
data: () => ({ unit: 1 }),
computed: {
...mapState("CounterAbout", ["count"]),
...mapState("PersonAbout", ["name"]),
},
methods: {
changeName() {
this.$store.dispatch("PersonAbout/CHANGE_NAME", 1);
},
},
};
</script>