在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)
      })
Logo

前往低代码交流专区

更多推荐