动作中的 Vuex 访问状态很奇怪

Vuex access states in actions weird

我有一个这样的 Vuex 商店。使用 this.$store.dispatch("storeTest"); 从我的组件触发 storeTest 操作时,我需要使用这种奇怪的语法 store.store 来访问项目。

import Vue from "vue";
import Vuex from "vuex";

Vue.use(Vuex);

export default new Vuex.Store({
  state: {
    loading: false,
    fileStr: "data.json",
  },
  actions: {
    storeTest(state) {
     //works
      console.log("state: ", state.state.fileStr);
     //fail
      console.log("state: ", state.fileStr);
    },
    },
  },
});

我希望我可以使用 state.item 访问状态。相反,我必须写 state.state.item。有什么问题吗?

动作函数的第一个参数不是 state,而是 context(参见 docs)。

此“上下文”对象具有多种属性,其中之一是 state

这与第一个参数为 state 的突变不同。

这是因为动作不接收状态作为参数,而是上下文。您需要它来分派其他操作或提交。

actions: {
  async myAction ({ state, dispatch, commit }) {
    console.log(state.loading);
    await dispatch('anotherAction')
    commit('someCommit')
  }
}

上下文属性的完整列表here

感谢@FitzFish

import Vue from "vue";
import Vuex from "vuex";

Vue.use(Vuex);

export default new Vuex.Store({
  state: {
    loading: false,
    fileStr: "data.json",
  },
  actions: {
    storeTest(context) {
     //works
      console.log("state: ", context.state.fileStr);
    },
  },
});