您现在的位置:首页 >> 前端 >> 内容

axios请求失败,TypeError:Cannotsetproperty'article'ofundefinedvue的解决办法

时间:2018/5/31 14:45:35 点击:

  核心提示:调试vue程序,使用axios请求后台报错,源码如下:getGoodsList () { axios.get(/v1/random) .then(function (response) { this....

调试vue程序,使用axios请求后台报错,源码如下:

getGoodsList () {
       axios.get('/v1/random')
         .then(function (response) {
           this.article = 'sss'
           console.log(response.title)
           console.log(response)
         })
         .catch(function (error) {
           console.log(error)
         })
    }
  },

报错为:TypeError: Cannot set property ‘article’ of undefined vue

axios请求后article 发生变化,而我使用的是名字函数,this 关键字是匿名函数,你是vue实例,改成箭头函数就行,如下:

getGoodsList () {
      // axios.get('/v1/random')
      //   .then(function (response) {
      //     this.article = 'sss'
      //     console.log(response.title)
      //     console.log(response)
      //   })
      //   .catch(function (error) {
      //     console.log(error)
      //   })
      axios.get('/v1/random').then((response) => {
        this.article = 'sss'
      })
    }

Tags:AX XI IO OS 
作者:网络 来源:周二也被占用