iT邦幫忙

2019 iT 邦幫忙鐵人賽

DAY 30
1
Modern Web

菜菜菜的 Vue 30天系列 第 30

vuex(namespaced)

菜菜菜的 Vue 30天 - Day30

今天要介紹的是 modules 內的 namespaced。

前一章有提到我要去取得其他 module 的 state 及 getters 我們要使用 rootState 及 rootGetters,那如果我要使用其他 module 裡面的 mutation 及 actions 呢?!

這時我們就需要在 module 裡面加上 namespaced 囉,使用 namespaced 也能夠提高 module 的封裝度和複用性,所有 getter 、 action 及 mutation 都會自動根據 module 註冊的路徑調整命名。

這樣說可能很抽象,下面就用範例來解說唄~

namespaced

沿用前一章的範例,我想要從 cart 去呼叫 product 的 mutations 及 actions 的話該如何執行,如下:

如上面所說,我將 module 內設定 namespaced: true,這樣就能呼叫其他 module 的 actions 及 mutations

const cart = {
    namespaced: true,
    state: {
        cartList: []
    },
    actions: {
        getList({commit, dispath, state, getters, rootState, rootGetters}) {
            commit('product/setList', payload, {root: true})
            //commit 及 dispath 沒有提供像 rootstate 及 rootGetters 的方法
            //所以使用 namespaced 時在最後面加上 root: true 
            //來讓這個 actions 可以呼叫其他的 mutations 及 actions
        }
    }
}

const product = {
    namespaced: true,
    state: {
        productList: []
    },
    mutations: {
        setList(state, payload) {
            state.productList.push(...payload)
        }
    }
}

另外一種情況是,我有可能在不同的 module 裡面的 actions 或 mutations 命名是一樣的,我們也能透過 namespaced 來明確的指定我們是要使用哪個 module 裡面的 actions 及 mutations。

const cart = {
    namespaced: true,
    state: {
        cartList: []
    },
    actions: {
        getList({commit, dispath, state, getters, rootState, rootGetters}) {
            xxxxxxx
        }
    }
}

const product = {
    namespaced: true,
    state: {
        productList: []
    },
    actions: {
        getList({commit, dispath, state, getters, rootState, rootGetters}) {
            xxxxxxxx
        }
    }
}

我們在 Vue 裡面就能透過以下方式來明確指定我是要哪個 actions:

this.$store.dispath('cart/getList');
this.$store.dispath('product/getList');

以上就是 Vuex 裡的 namespaced 囉~


上一篇
Vuex(modules)
系列文
菜菜菜的 Vue 30天30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言