vue中进行axios遇到的问题

错误如下:

NetData.vue?853e:26 Uncaught (in promise) TypeError: Cannot set property 'info' of undefined
    at eval (NetData.vue?853e:26)

具体代码:

 data () {
    return {
      info: null
    }
  },

methods: {

    getData () {
      // eslint-disable-next-line no-undef
      console.log(this)
        var self = this
      this.axios.get('https://api.coindesk.com/v1/bpi/currentprice.json')
        .then(function (response) {
          console.log(this)
          self.info = response
          console.log(response)
        })
    }
  }

错误原因是:在then函数内部this为undefined,已经不是外面的vue实例,解决方法就是设置一个变量把this存起来

var self = this

后面的this.info变成self.info,之后就可以正常赋值了

 

另一种方式是使用箭头函数也可以实现上面的效果,就不需要另外定义一个变量了,更加简单

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值