vuex 動態(tài)注冊方法 registerModule的實現(xiàn)
Vuex(2.3.0+)可以用store.registerModule方法在進(jìn)入路由時進(jìn)行注冊,離開路由時候銷毀 actions, mutations, getters, state,在一定范圍內(nèi)相同名稱不會被覆寫
例子
index.js
傳this 的寫法
module.exports = {
install(_this) {
_this.$store.registerModule(['abc'], {
namespaced: true,
state: {
rightTest: 999
},
actions: {
setTest: ({commit}, val) => {
commit('putTest', val)
}
},
mutations: {
putTest: (state, val) => {
state.rightTest = val;
}
}
})
},
uninstall(_this) {
_this.$store.unregisterModule(['abc'])
}
};
不傳this,有寫 store 的寫法
import store from '../../store';
export default {
install() {
store.registerModule(['abc'], {
namespaced: true,
state: {
rightTest: 999
},
actions: {
setTest: ({commit}, val) => {
commit('putTest', val)
}
},
mutations: {
putTest: (state, val) => {
state.rightTest = val;
}
}
})
},
uninstall() {
store.unregisterModule(['abc'])
}
}
調(diào)用方法時應(yīng)該在創(chuàng)建完實例之后的鉤子中,未創(chuàng)建實例調(diào)用會找不到 store。
在install、uninstall時,傳遞this過去,可以在上面中直接調(diào)用。
dispath 時,如果設(shè)置了命名空間,則一定要加上,我這個因為沒使用較復(fù)雜的命名,注冊時的名字就在命名空間那用了。
test.vue
import abc from '../../store/test';
...
created() {
// 掛載對應(yīng)的 store
abc.install(this);
console.log(this.$store, 'install');
},
destroyed() {
// 銷毀對應(yīng)的 store
abc.uninstall(this);
console.info(this.$store, 'uninstall');
},
methods: {
test(){
this.$store.dispatch('abc/setTest', Math.random());
}
總結(jié)
當(dāng)范圍內(nèi)使用動態(tài)方法注冊 actions 時還是比較爽的,而且在destroyed 鉤子中銷毀可以節(jié)省一部分資源;
配置命名空間也可以避免覆蓋問題,算是多一種手段吧(感覺還是應(yīng)用在多模塊,全局注冊時用到這個);
當(dāng)沒有父子關(guān)系時,但還需要多頁面共享狀態(tài),可以用動態(tài)注冊就不太方便了;
(我好像還是沒解決全局注冊時方法過多的問題。。。)
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
使用electron-builder將項目打包成桌面程序的詳細(xì)教程
這篇文章主要介紹了使用electron-builder把web端的項目打包生成桌面程序,并可安裝程序,文中通過代碼示例和圖文結(jié)合的方式給大家介紹的非常詳細(xì),具有一定的參考價值,需要的朋友可以參考下2024-08-08
vue3使用threejs實現(xiàn)3D卡片水平旋轉(zhuǎn)效果的示例代碼
這篇文章主要介紹了在vue3中使用threejs實現(xiàn)3D卡片水平旋轉(zhuǎn)效果,文中通過代碼示例講解的非常詳細(xì),對大家的學(xué)習(xí)或工作有一定的幫助,需要的朋友可以參考下2024-04-04

