我正在与Vuex
一起工作,遇到了一个可以自己解决的问题。问题是我创建的操作未在Vue组件内的方法created
的状态下返回数据。只需在新的Promise之前添加return
即可解决此问题。
这样就解决了问题,但我不太了解使用return可以解决问题的区别。有回报有什么区别?
这是我创建的函数,该函数在将return与操作一起使用之前并未在初始加载时加载数据
created () {
this.$store.dispatch('updateNews')
.then( response => {
this.news = this.$store.getters.getNews
})
.catch( error => this.error = "Error happened during fetching news" );
},
这是我添加退货后的商店
import Vue from "vue";
import Vuex from "vuex";
import axios from 'axios';
Vue.use(Vuex);
export default new Vuex.Store({
state: {
news: []
},
getters:{
getNews(state){
return state.news
}
},
mutations: {
UPDATE_NEWS(state, payload){
state.news = payload
}
},
actions: {
updateNews(context){
var url = 'https://newsapi.org/v2/top-headlines?' +
'country=us&' +
'apiKey=something';
return new Promise ( (res, rej) => {
axios
.get(url)
.then(response => {
context.commit('UPDATE_NEWS', response.data)
res()
})
.catch( error => rej() )
})
}
},
});
答案 0 :(得分:0)
一个promise不能作为一个函数内部的简单声明,您实际上已经返回了promise来使用它。这里的情况有点奇怪,因为axios已经返回了可以使用的承诺。我认为问题在于,当诸如此类的正确流程将通过计算属性访问该值时,您想以编程方式将存储状态下的变量值赋给组件数据中的变量:
Vuex
import Vue from "vue";
import Vuex from "vuex";
import axios from 'axios';
Vue.use(Vuex);
export default new Vuex.Store({
state: {
news: []
},
getters:{
getNews(state){
return state.news
}
},
mutations: {
UPDATE_NEWS(state, payload){
state.news = payload
}
},
actions: {
updateNews(context){
var url = 'https://newsapi.org/v2/top-headlines?' +
'country=us&' +
'apiKey=something';
axios
.get(url)
.then(response => {
context.commit('UPDATE_NEWS', response.data)
})
.catch( error => console.log('Oops, something went wrong with the news', error) );
}
},
});
组件
created () {
this.$store.dispatch('updateNews');
},
computed: {
news() {
return this.$store.getters.getNews;
}
}
像这样使用它,您不必在组件数据中创建名为news的变量,只需在计算属性中进行访问,就如同访问组件数据中返回的变量一样,就可以访问它