【发布时间】:2019-08-21 18:54:26
【问题描述】:
我的问题是返回初始状态的吸气剂 ([])。
在我的组件中,我有一个 created 方法,可以将 axios 调用结果设置为状态。
created() {this.$store.dispatch("SET_STORIES");},
我在计算中有 mapGetters:
computed: {
...mapGetters(["GET_STORIES"])
},
还有一个获取状态的方法:
methods: {
stories() {
return this.$store.getters.GET_STORIES;
}
}
mounted() 正在返回一个空数组:
mounted() {
console.log("stories", this.$store.getters.GET_STORIES);
},
store.js
import Vue from "vue";
import Vuex from "vuex";
import axios from "axios";
import VueAxios from "vue-axios";
import chunk from "lodash/chunk";
Vue.use(Vuex, VueAxios, axios);
export default new Vuex.Store({
state: {
stories: [],
twoChunkStories: []
},
getters: {
GET_STORIES: state => {
return state.stories;
}
},
mutations: {
SET_STORIES(state, stories) {
state.stories = stories;
},
SET_CHUNKED_STORIES(state, stories) {
state.twoChunkStories= stories;
},
},
actions: {
SET_STORIES: async ({ commit }) => {
const options = {
headers: {
"Content-Type": "application/json"
}
};
let { data } = await axios.get(
"https://api.example.com/get.json",
options
);
if (data.meta.code === 200) {
let storiesArray = data.data.stories;
let chunkSize = 2;
commit("SET_STORIES", storiesArray);
let chunkedArray = chunk(storiesArray, chunkSize);
commit("SET_CHUNKED_STORIES", chunkedArray);
}
}
}
});
如何进行 axios 异步调用,在最早的生命周期钩子上设置 onload 状态(我认为 created() 是最早的钩子)并准备好在挂载时调用。我显然在 getter 上异步做错了什么,我只是不知道到底是什么。
【问题讨论】:
标签: javascript vue.js