用了vuex,在action里定义了一个发请求并把数据放在state里方法
actions: {
GET_LIST_DATA: ({state },url) => {
axios.get(url)
.then(function (response) {
state.good=response.data.data
console.log(state.good)
})
.catch(function (error) {
console.log(error);
});
}
},
在一个组件的mounted里调用这个action之后获取state
mounted() {
this.$store.dispatch('GET_LIST_DATA','https://cnodejs.org/api/v1/topics')
.then(() => {
this.dataList = this.$store.state.good
console.log(this.$store.state.good)
})
},
页面第一次打开时,执行顺序为请求成功后打印这个state,刷新页面时,请求依然成功了,但state就变成undefined了,不知道是不是请求还没成功就打印了。
箭头函数的this指向问题,换成function就好了,或者用闭包把this保存到变量传入箭头函数里