模块化思想
我们之前的博文已经讲述了Vuex怎么使用命名空间实现模块化状态管理。详情可以看:
Vuex命名空间及如何获取根模块、兄弟模块状态管理器_AI3D_WebEngineer的博客-CSDN博客https://blog.csdn.net/weixin_42274805/article/details/133269196?ops_request_misc=%257B%2522request%255Fid%2522%253A%2522169839448016800182196324%2522%252C%2522scm%2522%253A%252220140713.130102334.pc%255Fblog.%2522%257D&request_id=169839448016800182196324&biz_id=0&utm_medium=distribute.pc_search_result.none-task-blog-2~blog~first_rank_ecpm_v1~rank_v31_ecpm-1-133269196-null-null.nonecase&utm_term=%E5%91%BD%E5%90%8D%E7%A9%BA%E9%97%B4&spm=1018.2226.3001.4450
动态模块场景
动态模块的设计理念是为了方便前端随时挂载和卸载状态管理器模块。
模块书写
import { dailyStatistics, getList } from '@/api/perception/index.js';
export const INSTALL_MODULE_PATH = 'moduleStore/perception';
export default {
namespaced: true,
state: {
dailyStatistics: {},
recordsList: {}
},
mutations: {
saveDailyStatistics(state, loadData) {
state.dailyStatistics = loadData;
},
saveRecordsList(state,loadData) {
state.recordsList = loadData
}
},
actions: {
/**
* @name 获取数据
*/
getDailyStatistics({ commit }) {
return dailyStatistics().then(res => {
commit('saveDailyStatistics', res.data || {});
});
},
getRecordsList({ commit }, {pageA,stepNum,info}) {
...
commit('saveRecordsList', {
total:res.data.total,
list
})
});
}
},
getters: {},
};
与正常的模块没什么区别的,只是多导出了一个路径变量。用于指定她在仓库里的位置。
挂载和卸载
import PERCEPTION_MODULE, {INSTALL_MODULE_PATH,} from '@/store/modules/perception';
beforeCreate() {
// 注册状态管理器模块
this.$store.registerModule(INSTALL_MODULE_PATH, PERCEPTION_MODULE);
},
beforeDestroy() {
// 卸载管理器模块
this.$store.unregisterModule(INSTALL_MODULE_PATH);
},
此时挂载上去的仓库位于this.$store.moduleStore/perception里
使用
// 调用actions
await this.$store.dispatch(`${INSTALL_MODULE_PATH}/getRecordsList`, {...});
// 调用仓库
this.$store.state[INSTALL_MODULE_PATH].xxxx
// 调用mutations
this.$store.commit(`${INSTALL_MODULE_PATH}/saveDailyStatistics`, {...});
// 调用getter
this.$store.getters[INSTALL_MODULE_PATH].xxxx