请稍等 ...
×

采纳答案成功!

向帮助你的同学说点啥吧!感谢那些助人为乐的人

axios里使用this报错?

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回答

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

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


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


0 回复 有任何疑惑可以回复我~
  • 提问者 momoJOJO #1
    非常感谢!谢谢老师
    回复 有任何疑惑可以回复我~ 2018-03-06 10:24:15
问题已解决,确定采纳
还有疑问,暂不采纳
意见反馈 帮助中心 APP下载
官方微信