首先来说下我的bug
因为把 namespaced 写成了 namespace 少写了一个 d 导致我在页面里调用 dispatch 的时候一直很奇怪为啥 dispatch('xxx') 加了模块路径比如下文提到的 A/xxxx 这种就会报错告诉我找不到这个 action 方法
和大家分享下 namespaced 这个属性
环境是 vue3+ts
可能是我没有认真看 vuex 的 namespaced 属性
这个属性在使用 vuex 的 modules 时调用 dispatch 、 commit 、 getters 时 决定传入的第一参数type里是否需要加 modules 里的key 作为路径
举个例子 store/index.js
import { createStore } from "vuex";
import getters from ./getters;
import A from ./modules/A
import B from ./modules/B
export default createStore({
getters,
//方便大家区分这里的key 使用 keyA 做一个区分
modules:{
keyA:A,
keyB:B
},
});
store/modules/A.ts
const state = {
userInfo: {},
};
const mutations = {
SET_USER_INFO(state: any, payload: any) {
state.userInfo = payload;
},
};
const actions = {
getUserInfo({ commit }: { commit: (key: string, payload: any) => any }) {
commit("SET_USER_INFO", res);
},
};
export default {
namespaced: true,
state,
actions,
mutations,
};
store/modules/B.ts
const state = {};
const mutations = {};
const actions = {
getUserInfo() {},
getData(){}
};
export default {
namespaced: true,
state,
actions,
mutations,
};
如果写了 namespaced 这个属性并且为true时 在使用 dispatch 时得这样用
import { useStore } from 'vuex'
const store = useStore()
//这里得加上modules的 key 也就是keyA
store.dispatch('keyA/getUserInfo')
如果没写 namespaced 或者不为 true 的话这里的 dispatch 就变成
store.dispatch('getUserInfo')
如果 A 和 B 模块里都有同名的方法,那么在 dispatch 这个同名的 action 时会都执行一次(测试过都会执行)。commit 、getters 同理
所以如果使用了 modules 的话最好还是得使用一下这个属性
贴一下在模块多的情况下更好的使用modules的代码 参考自 vue-element-admin
import { createStore, createLogger } from "vuex";
import getters from "./getters";
const debug = process.env.NODE_ENV !== "production";
const modulesFiles = require.context("./modules", true, /\.ts$/);
const modules = modulesFiles.keys().reduce((modules, modulePath) => {
const moduleName = modulePath.replace(/^\.\/(.*)\.\w+$/, "$1");
const value = modulesFiles(modulePath);
modules[moduleName] = value.default;
return modules;
}, {});
export default createStore({
getters,
modules,
strict: debug,
plugins: debug ? [createLogger()] : [],
});
以上就是关于这次vuex4踩坑日记的全部内容啦
文章写的不多,如有问题或者相关问题可在评论区评论或者私信
如果这篇文章帮到了你,麻烦帮忙点赞哦!