Vuex modules的使用

1 为什么要使用模块

当应用变得复杂时,store对象就会变得相当臃肿,为了解决这个问题,可以将store分割成模块(module)。而每个模块拥有自己的store mutation action getter等

2 代码

2.1 分割模块与定义模块

srcstoreindex.js

  modules:{
    a:moduleA,
    b:moduleB
  }
//2 创建对象
const moduleA = {
  state:{
    name:'张三'
  },
  getters:{
    fullname(state){
      return state.name + '先生'
    },
    fullname2(state,getters,rootState){
      return getters.fullname + rootState.counter
    }
  },
  mutations:{
    updateName(state,payload) {
      state.name = payload
    }
  },

  actions:{
    aUupdateName(context){
      //模块里的commit 只能commit到自己模块里的mutations,
      setTimeout(()=>{
        context.commit('updateName','王五')
      },1000)
    }
  },
  //模块里基本不会再分割
  modules:{}
}

2.2 使用模块 srcApp.vue

    <h2>{{$store.state.a.name}}</h2>
    <h2>{{$store.getters.fullname}}</h2>
    <h5>{{$store.getters.fullname2}}</h5>
    <button @click="updateName">修改名字</button>
    <button @click="asyncUpdateName">异步修改名字</button>
      updateName(){
        this.$store.commit('updateName','李四')
      },
      asyncUpdateName(){
        this.$store.dispatch('aUupdateName')
      }

页面展示结果

原文地址:https://www.cnblogs.com/polax/p/13252702.html