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>


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM