为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

陪伴而非守候 2018-10-10 13:23:35
用了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之后获取statemounted() {    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了,不知道是不是请求还没成功就打印了。
查看完整描述

1 回答

?
Cats萌萌

TA贡献1805条经验 获得超9个赞

你打印的时候 你还没有请求成功。你应该在请求成功时候返回一个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)

      });

    }  

}


查看完整回答
反对 回复 2018-11-25
  • 1 回答
  • 0 关注
  • 1404 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号