vuex遇到的坑:vuex模塊化下,一個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,
};

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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章