vue使用axios获取数据页面刷新时出错

用了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了,不知道是不是请求还没成功就打印了。

阅读 7.3k
2 个回答

箭头函数的this指向问题,换成function就好了,或者用闭包把this保存到变量传入箭头函数里

你打印的时候 你还没有请求成功。你应该在请求成功时候返回一个promise 通知你的组件去执行

GET_LIST_DATA: ({state}, url) => {
    return new Promise(resolve, reject) => {
     axios.get(url)
      .then(function (response) {
        state.good=response.data.data
        console.log(state.good)
        resolve()
      })
      .catch(function (error) {
        console.log(error);
        reject(error)
      });
    }  
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题