我的vuex模块文件目录
现在,我想在user.js中调用app.js文件中的action方法,怎么办呢?
app.js内容如下:
const state = {
cachedViews: [], // 缓存view
};
const mutations = {
DEL_ALL_CACHED_VIEWS: (state) => {
state.cachedViews = [];
},
};
const actions = {
// 清空缓存view
delAllCachedViews({ commit, state }) {
return new Promise((resolve) => {
commit("DEL_ALL_CACHED_VIEWS");
resolve([...state.cachedViews]);
});
},
};
export default {
namespaced: true,
state,
mutations,
actions,
};
user.js如下:
import { login, logout} from "@/api/user";
const state = {
token: '',
};
const mutations = {
SET_TOKEN: (state, token) => {
state.token = token;
},
};
const actions = {
// 用户登出
logout({ commit, dispatch, state }) {
return new Promise((resolve, reject) => {
logout()
.then(() => {
commit("SET_TOKEN", ""); // 退出时清空token
dispatch("app/delAllCachedViews", {}, { root: true });
resolve();
})
.catch((error) => {
reject(error);
});
});
},
};
export default {
namespaced: true,
state,
mutations,
actions,
};
在这样,就可以在user.js这个模块中调用app.js模块的action方法啦。
上面的代码中dispatch("app/delAllCachedViews", {}, { root: true });
就是在模块 B 调用 模块 A 的 actions,
有 3 个参数, 第一个参数是其他模块的 actions 路径, 第二个是传给 actions 的数据, 如果不需要传数据, 也必须预留为{}, 第三个参数是配置选项, 申明这个 acitons 不是当前模块的
类似的,调用其他的mutation,state等,方法都是类似的。具体看参考文档:
1、Vuex 模块化+命名空间后, 如何调用其他模块的 state, actions, mutations, getters?
https://segmentfault.com/a/1190000009434398