vue(30)vuex使用子模块

如果项目很大再store的index.js里面可能就有很多的内容,不便于管理,vuex支持在主模块下面创建子模块:

store/index.js:

import { createStore } from 'vuex'
//新建一个子模块,也可以将这个子模块写在外面的一个js文件中,这里引入
const user = {
  state: {
    userName: 'jack',
    password: '123'
  },
  getters:{
    //rootState可以访问父模块的state中的内容
    fullName(state,getter,rootState){
      return state.userName + " " +rootState.name;
    }
  },
  mutations: {
    changeUserName(state,payload){
      state.userName = payload;
    }
  },
  actions:{
    //context中有state(自己模块的state),commit(自己模块的mutations),getters(自己模块的getters),
    //rootGetters(父模块的getters),rootState(父模块的state)
    smt(context,payload){
      setTimeout(()=>{
        //用父模块的name赋值给子模块的uaerName
        context.commit('changeUserName',context.rootState.name);
      },2000);
    }
  }

}

export default createStore({
  state: {
    name: 'tom',
    age: '10'
  },
  mutations: {
  },
  actions: {
  },
//挂载子模块
  modules: {
    user
  }
})
 
 
 
访问子模块中的各个对象:
<template>
  <div class="about">
    <h1>{{$store.state.user.userName}}</h1>
    <button @click="click1()">改变user模块中的userName值</button>
    <h1>调用模块中的getters:{{$store.getters.fullName}}</h1>
     <button @click="click2()">调用模块中的action 2s后改变值</button>
  </div>
</template>

<script>
export default {
  name: 'About',
  methods: {
    click1(){
      //调用子模块的mutations中的方法时不用加上子模块的名称,vue会在所有模块中搜索,所有要保持所有模块中mutations中的方法名都不一样
      this.$store.commit('changeUserName','maycpou');
    },
    click2(){
      //调用子模块的action一样,不需要子模块的名称,所以要保持方法名不同
      this.$store.dispatch('smt','cp3');
    }
  }
}
</script>
posted @ 2021-07-03 11:57  maycpou  阅读(844)  评论(0编辑  收藏  举报