简体   繁体   English

从Vuex Action将Axios提取的数据分配给Vuex State

[英]Assigning Axios fetched data to Vuex State from Vuex Action

As per the Axios documentation , I concurrently fetch two data sources from my backed ( block.json and type.json ) within actions of my Vuex store. 根据Axios 文档 ,我在Vuex存储的actions中同时从支持的( block.jsontype.json )获取两个数据源。 In my Vuex State, I declare myBlocks and myTypes as data. 在我的Vuex状态中,我将myBlocksmyTypes声明为数据。 The data is fetched fine, but I cannot seem to assign the fetched data to the variables in the Vuex state. 数据可以很好地获取,但是我似乎无法将获取的数据分配给处于Vuex状态的变量。 I seem to have troubles referencing the state, because console.log(state.sample) yields undefined rather than foo . 我似乎在引用状态时遇到麻烦,因为console.log(state.sample)产生的是undefined而不是foo However, console.log(state) yields the following as in the photograph below. 但是, console.log(state)产生以下内容,如下图所示。 Any leads would be great. 任何线索都很好。 在此处输入图片说明

state: {
  sample: 'foo',
  myBlocks: [],
  myTypes: []

},


actions: {
  fetchElementColors: function(state) {
      function getElementBlockColors() { return axios.get('/element-data/block.json'); }
      function getCategoryDataColors() { return axios.get('/element-data/type.json'); }

      axios.all([getElementBlockColors(), getCategoryDataColors()])
        .then(axios.spread(function(blockData, categoryData) {
          console.log(state);
          console.log(state.sample);
          state.myBlocks= blockData.data;
          state.myTypes= categoryData.data;
        }));
    }

}

In your actions , you are not provided with state but context . 在您的actions ,没有为您提供state而是为您提供context

So you need to do as follows: 因此,您需要执行以下操作:

actions: {
  fetchElementColors: function(context) {
      function getElementBlockColors() { return axios.get('/element-data/block.json'); }
      function getCategoryDataColors() { return axios.get('/element-data/type.json'); }

      axios.all([getElementBlockColors(), getCategoryDataColors()])
        .then(axios.spread(function(blockData, categoryData) {
          console.log(context.state);
          console.log(context.state.sample);
          context.state.myBlocks= blockData.data;
          context.state.myTypes= categoryData.data;
        }));
    }

}

Reference: https://vuex.vuejs.org/guide/actions.html 参考: https : //vuex.vuejs.org/guide/actions.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM