Vuex(2.3.0+)可以用store.registerModule方法在進入路由時進行注冊,離開路由時候銷毀 actions, mutations, getters, state,在一定范圍內相同名稱不會被覆寫
例子
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']) }}調用方法時應該在創建完實例之后的鉤子中,未創建實例調用會找不到 store。
在install、uninstall時,傳遞this過去,可以在上面中直接調用。
dispath 時,如果設置了命名空間,則一定要加上,我這個因為沒使用較復雜的命名,注冊時的名字就在命名空間那用了。
test.vue
import abc from '../../store/test';...created() { // 掛載對應的 store abc.install(this); console.log(this.$store, 'install');},destroyed() { // 銷毀對應的 store abc.uninstall(this); console.info(this.$store, 'uninstall');},methods: { test(){ this.$store.dispatch('abc/setTest', Math.random()); }總結
當范圍內使用動態方法注冊 actions 時還是比較爽的,而且在destroyed 鉤子中銷毀可以節省一部分資源;
配置命名空間也可以避免覆蓋問題,算是多一種手段吧(感覺還是應用在多模塊,全局注冊時用到這個);
當沒有父子關系時,但還需要多頁面共享狀態,可以用動態注冊就不太方便了;
(我好像還是沒解決全局注冊時方法過多的問題。。。)
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持錯新站長站。
新聞熱點
疑難解答
圖片精選