Vuex由于使用单一状态树,应用的所有状态会集中到一个比较大的对象。当应用变得非常复杂时,store 对象就有可能变得相当臃肿。
因此,Vuex 允许我们将 store 分割成模块(module),每个模块拥有自己的 state、mutation、action、getter、甚至是嵌套子模块。
默认情况下,模块内部的 action、mutation 和 getter 是注册在全局命名空间的,这样使得多个模块能够对同一 mutation 或 action 作出响应。如果希望你的模块具有更高的封装度和复用性,此时就用到了命名空间这个概念。
Vuex模块引入操作:
about.vue
<template>
<div class="about">
<h1 @click="setMallname('Green')">{{mall.mallname}}</h1>
<h1 @click="setLuntanname('Gluntan')">{{luntanname}}</h1>
</div>
</template>
<script>
import { mapState,mapGetters, mapActions, mapMutations } from 'vuex'
export default{
mounted(){
console.log(this);
//触发vuex的action方法
// this.$store.dispatch('getJoke')
// this.getJoke()
},
methods:{
// addAge:function(){
// this.$store.commit('addAge', 3)
// }
...mapActions(['getJoke']),
...mapMutations(['addAge','getList','setMallname']),
...mapMutations('luntan',['setLuntanname']) //设置命名空间后,引入方式有所不同。
},
computed:{
...mapState(['mall']), //结构mapState
...mapState('luntan',['luntanname'])
}
}
</script>
设置命名空间后,引入方式有所不同。…mapMutations(‘luntan’,[‘setLuntanname’]) 先导入luntan名称,然后设置引入属性
luntan.js
export default {
namespaced:true,
state : {
luntanname:"格林lt"
},
mutations:{
setLuntanname:function(state,payload){
state.luntanname = payload
}
}
}
index.js
import luntan from './luntan'
modules: {
luntan
}