Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/vue.js/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Vue.js 如何在创建Vuex.Store对象或定义初始值期间运行变异?_Vue.js_Initialization_Vuex - Fatal编程技术网

Vue.js 如何在创建Vuex.Store对象或定义初始值期间运行变异?

Vue.js 如何在创建Vuex.Store对象或定义初始值期间运行变异?,vue.js,initialization,vuex,Vue.js,Initialization,Vuex,我有一个数组。我通过RESTAPI获取数据。我可以从任何组件调用变异getData(),但我需要在创建对象Vuex.Store时自动调用它,我可以这样做吗 export default new Vuex.Store({ state: { myArray: [], }, mutations: { getData() { //get data from remote API and pass to myArray ax

我有一个数组。我通过RESTAPI获取数据。我可以从任何组件调用变异
getData()
,但我需要在创建对象
Vuex.Store
时自动调用它,我可以这样做吗

export default new Vuex.Store({

state: {
    myArray: [],       
},

 mutations: {

    getData() {
       
       //get data from remote API and pass to myArray
       axios.post('').then(response => {
             this.myArray = response.data;
       };
    }
  }
 })

第一件事:突变是同步纯函数。这意味着您的突变不应有副作用,并且在突变结束时,存储的状态应更新为新状态。Axios使用承诺,因此是异步的。你应该在行动中做到这一点

至于自动执行数据提取,您可以在定义存储的文件中执行,也可以在生命周期挂钩的Vue入口点(例如App.Vue)中执行。请记住,axios调用是异步的,这意味着您的应用程序将在后台加载数据时加载。你得设法处理这个案子

// store.js
import Vue from 'vue';
import Vuex from 'vuex';

const store = new Vuex.Store({
  state: {
    myArray: [],
  },
  mutations: {
    setMyArray(state, payload) {
      Vue.set(state, 'myArray', payload);
    },
  },
  actions: {
    fetchData({ commit }) {
      axios.post('').then(response => {
        commit('setMyArray', response.data);
      };
    }
  }
});

// Setup
Vue.use(Vuex);

// Now that we have a store, we can literally just call actions like we normally would within Vue
store.dispatch('fetchData');

// Keep in mind that action is not blocking execution. Execution will continue while data is fetching in the background

非常感谢你!祝你万事如意!