我有个阵列。我通过rest获取数据。我可以从任何组件调用一个变异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;
};
}
}
})
发布于 2020-09-14 17:57:12
首先:突变是同步纯函数。这意味着您的突变不应该有副作用,并且在您的突变结束时,您的存储状态应该更新到新的状态。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
https://stackoverflow.com/questions/63889202
复制相似问题