this指向问题

来源:6-5 使用 Mockjs 来模拟数据

笨小熊的一天

2017-08-08

http://szimg.mukewang.com/59895f400001466606500303.jpg

这块得this指的是什么,和箭头函数有什么关系?没听懂老师里面讲的什么意思

写回答

1回答

fishenal

2017-08-09

this是当前组件,箭头函数的意思是这样,如果这么写:


// 这里的this是导出组件对象的this,包含了data, props等等,可以理解为这个组件本身

this.$http.get('xxx').then(function () {

        // 这里的this是匿名函数体里的this,所以如果用this.newsList会发现不存在

        console.log(this)

})



如果用箭头函数


// 这里的this是导出组件对象的this,包含了data, props等等,可以理解为这个组件本身

this.$http.get('xxx').then( (res) => {

        // 现在的this跟匿名函数外面的this保持一致,可以获取到this.newsList

        console.log(this)

})


如果不用箭头函数,需要通过一个变量把外层的this传递进去:


// 这里的this是导出组件对象的this,包含了data, props等等,可以理解为这个组件本身

var me = this

this.$http.get('xxx').then(function () {

        console.log(this.newsList) // undefined

        console.log(me.newsList) // 成功得到组件的属性

})


1
2
笨小熊的一天
匿名函数this不会指向上下文,箭头函数this会指向上下文,是这个意思吧
2017-08-09
共2条回复

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

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

3966 学习 · 999 问题

查看课程