vuex梳理5 模塊化modules 以及命名空間namespaced的使用


在vuex的使用中經常會根據不同業務模塊,也將vuex內部按不同模塊進行使用,每個模塊中同樣分為state,mutations,actions,getters這幾個部分

import Vue from 'vue'
import Vuex from 'vuex'
import adv from "./adv"
import goods from "./goods"
import user from "./user"

Vue.use(Vuex)

export default new Vuex.Store({

    state: {
        father: "發澤"
    },
    mutations: {
        SET_TITLE() {
            console.log("father,lalalalala");
        },

    },
    getters: {
        sums() {
            return 5;
        }
    },
    // 模塊,將你的store進行了模塊化。
    modules: {
        adv, // 廣告模塊
        goods, // 商品模塊
        user //用戶模塊
    }
})

默認情況下,模塊內部的 action、mutation 和 getter 是注冊在全局命名空間的——這樣使得多個模塊能夠對同一 mutation 或 action 作出響應。

所以在不使用命名空間的情況下,在組件中直接通過 commit,和dispatch,getters來調用即可,不用添加對應模塊的名字

this.$store.dispatch('teaction')
this.$store.commit('TEST_MUA')
this.$store.getters.sumss

需要注意的是,如果不同模塊action和mutation內的函數名相同時,會同時調用所以名稱相同的函數,不同模塊下getters的函數則不允許重名

state不受命名空間的影響使用時需要加模塊名稱

this.$store.state.goods.goodsTitle  // goods代表模塊名稱

使用命名空間時調用是要加模塊名稱,不加模塊名則調用公共函數

this.$store.dispatch('adv/teaction')
  this.$store.getters['adv/sumsss']

在使用了命名空間的module中,若需要在全局命名空間內分發 action 或提交 mutation,將 { root: true } 作為第三參數傳給 dispatch 或 commit 即可。如果不加則默認調用當前模塊內的函數

 

const actions = {
    teaction({
        dispatch,
        commit,
        getters,
        rootGetters
    }, params) {
        console.log('modal adv action', getters, rootGetters)
        commit('SET_TITLE', {}, {
            root: true
        })
    },
   
};

 

下面解釋一下個參數的含義

在某一midule中

mutations: {
      
        TEST_MUA(state,) {
            // this.commit('adv/SET_TITLE', null, )
            console.log('modal goods mutations', state, this.state)
            this.dispatch('goodsavc')
       state代表當前模塊中的state,this.state則表示整個store中的state } }, actions: { goodsavc({ commit,
       state rootState, rootGetters, getters }, params) { console.log(
'aaaaaaaaaaaaa', rootState, rootGetters, getters) this.dispatch('run') }, state代表當前模塊的state當然,不推薦在actions中直接修改state要同mutations進行操作
    rootState中可以獲取到整個store中不同模塊的數據 
    getters和rootGetters在不使用命名空間的情況下都代表store中所有的getters
    在使用命名空間時,getters代表當前模塊getters,rootGetters代表store中所有getters
}, getters: { sumss(state, getter, rootState, rootGetters) { console.log(
'modal goods getters', getter, rootState, state, ) return 3; }, 同上 }

 


免責聲明!

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



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