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

How i can run mutation during creation Vuex.Store object or define the initial value?

我有一个数组。我通过 rest api 为它获取数据。我可以从任何组件调用突变 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;
       };
    }
  }
 })

首先要做的事情是:突变是同步纯函数。这意味着你的突变不应该有 side-effects,并且在你的突变结束时,你的商店状态应该更新到新状态。 Axios 使用 promises,因此是异步的。你应该在一个动作中做到这一点!

至于自动执行数据获取,您可以在定义商店的文件中执行此操作,也可以在生命周期挂钩中的 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