当前位置:   article > 正文

vuex遇到的坑:vuex模块化下,一个store模块文件中调用另外一个模块的action方法_store 调用其他模块的action

store 调用其他模块的action

我的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,
};

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27

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,
};

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36

在这样,就可以在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

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小丑西瓜9/article/detail/280147
推荐阅读
相关标签
  

闽ICP备14008679号