axios里使用this报错?

来源:6-4 使用 axios 发送数据请求

momoJOJO

2018-03-05

axios.get('api/getNewsList')
  .then((res) => {
    console.log(res)
    this.newsList = res.data.list
  })

使用老师的语法没问题,但是使用axiosapi提供的的语法

axios.get('api/getNewsList')
  .then(function (res) {
    console.log(res)
    this.newsList=res.data.list
  })

会报错 Cannot set property 'newsList' of undefined,网上查了查是this指向了全局,这里是不是只能用箭头函数

写回答

1回答

fishenal

2018-03-05

是的,箭头函数内的this是代码环境的this,function里的this是执行环境的this。

用function可以通过me把this传进函数体里


var me = this
axios.get('').then(function () {
    console.log(me.newsList)
})


0
1
momoJOJO
非常感谢!谢谢老师
2018-03-06
共1条回复

最容易上手的Vue2.0入门实战教程

快速入门Vue2.0,组件化开发一个数字产品电商平台

3966 学习 · 999 问题

查看课程