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

陪伴而非守候
浏览 1405回答 1
1回答

Cats萌萌

你打印的时候 你还没有请求成功。你应该在请求成功时候返回一个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)      });    }  }
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript