VUE.JS 使用axios数据请求时数据绑定时 报错 TypeError: Cannot set property 'xxxx' of undefined 的解决办法

在axios里使用this.xxxx(xxxx为data里面定义的)报错

TypeError: Cannot set property 'xxxx' of undefined

主要原因是:

在 then的内部不能使用Vue的实例化的this, 因为在内部 this 没有被绑定。

解决办法:

1、用ES6箭头函数,箭头方法可以和父方法共享变量

 axios({
        method: 'get',
        url: 'http://127.0.0.1:8081/brand/list',
        data: {
        },
        dataType: 'json',
        ContentType: 'application/json;charset-utf-8',
        headers: {
          'ContentType': 'application/json'
        }
      }).then(response => {
        console.log('获取数据response:' + response)
        this.brands = response.data
        console.log('brands:' + this.brands)
      }).catch( error => {
        console.log(error)
      })

2、在请求axios外面定义一下 var that=this

 var that = this
 axios({
        method: 'get',
        url: 'http://127.0.0.1:8081/brand/list',
        data: {
        },
        dataType: 'json',
        ContentType: 'application/json;charset-utf-8',
        headers: {
          'ContentType': 'application/json'
        }
      }).then(function (response) {
        console.log('获取数据response:' + response)
        that.brands = response.data
        console.log('brands:' + that.brands)
      }).catch(function (error) {
        console.log(error)
      })
  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值