Vuex modules的使用

Posted polax

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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‘)
      }

页面展示结果

技术图片

 

以上是关于Vuex modules的使用的主要内容,如果未能解决你的问题,请参考以下文章

vuex中的模块化(modules)和命名空间(namespaced),以及四个辅助函数

使用 NuxtJS 和 vuex-module-decorators 的动态 vuex 存储模块

uni-app 使用vuex(vuex module)

VUEX 使用学习六 : modules

Vuex进阶使用之modules模块化划分mapStatemapActions辅助函数的使用

vue中vuex的使用, vuex使用模块化自动引入modules