1.复习vue2中vueX中的使用
import Vue from "vue";
import vuex from 'vuex'
import moduleA from "./module/moduleA";
import moduleB from "./module/moduleB";
Vue.use(vuex)
export default new vuex.Store({
state:{
a:9
},
getters:{
comA(state){
return state.a*2
}
},
mutations:{
syncChangeA(state,payload){
state.a +=payload
}
},
actions:{
AsyncChangeA({commit},payload){
setTimeout(() => {
commit('syncChangeA',payload)
}, 1000);
}
},
modules:{
moduleA,
moduleB
}
})
<template>
<div>
<h1>{{ a }}</h1>
<h1>{{ ma }}</h1>
<h1>{{ comA }}</h1>
<button @click="handleSyncChangeA">同步改变a</button>
<button @click="handleAsyncChangeA">异步改变a</button>
<button @click="handleNoNamespaced">没有命名空间</button>
</div>
</template>
<script>
import { mapState,mapGetters,mapMutations,mapActions } from 'vuex';
export default {
props: {
},
data() {
return {
};
},
computed:{
...mapState(['a','ma']),//9
...mapGetters(['comA'])//18
},
methods: {
...mapMutations(['syncChangeA','noNamespaced']),
...mapActions(['AsyncChangeA']),
handleSyncChangeA(){
this.syncChangeA(10);
},
handleAsyncChangeA(){
this.AsyncChangeA(1);
},
handleNoNamespaced(){
console.log(this.$store);
this.noNamespaced()
}
},
components: {
},
};
</script>
<style scoped lang="scss">
</style>
moduleA
export default {
// namespaced:true,
state:{
ma:1
},
mutations:{
noNamespaced(){
console.log('没有命名空间','moduleA');
}
},
}
moduleB
export default {
// namespaced:true,
state:{
ma:1
},
mutations:{
noNamespaced(){
console.log('没有命名空间','moduleB');
}
},
}
了解一下命名空间
当使用 模块化之后 模块的 全局的 state 内会 多一个属性 这个属性是一个对象,对象属性名就是注册的模块名,对象内包含的属性就是 注册的 模块state内的全部属性
所以不用 map函数就得 this.$store.state.moduleA.ma
但是模块的mutations 和 actions 不同 他们是和全局的 mutations 和 actions 混到一块了
如果不开 命名空间 模块内同名的函数会混在一个数组内 当调用的时候 ...mapMutations(["noNamespaced"]), 两个都会触发
当开启命名空间后
mutations内 会 加一个 以该模块名字为前缀的数组 调用的时候
...mapMutations("moduleA", ["noNamespaced"]), 第一个参数传 模块的名字