核心提示:调试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' }) }