关于箭头函数this指向问题
来源:6-9 首页 - 登录组件(1)

英姿飒爽豆腐块
2017-11-09
this.$http.post('api/login') .then((data) => { this.$emit() },(error) => { console.log(error) })
这里的第一个this指向的是哪里?是logform这个组件的全局吗?
箭头函数里面的this是指的这个箭头函数的执行环境吗?
在这之前的index.vue里面也出现过
this.$http.get('api/getNewsList') .then((res) => { this.newsList = res.data },(err) => { console.log(err) })
为什么写成this.newsList,即使不用箭头函数不也可以用this指向newsList吗?
求老师解答一下
2回答
-
不用箭头函数怎么能通过this访问组件呢。
如果
... .then(function () { console.log(this.newsList) // 这里的this.newsList undefined, 因为this是这个你匿名函数的this })
如果不用es6,要这么写
... var self = this .then(function () { console.log(self.newsList) // 通过self传递外层this,即组件本身 })
箭头函数就是可以避免了之前这种很蠢的this传递啊。
所有组件配置对象里出现的this,都是指这个组件本身。
export {
data () {
},
method: {
metA () {
//这里的 this 就理解为当前组件本身
}
}
}
每一个组件其实就是一个特定格式的js对象,通过组件树一层一层叠加到最上层跟组件,就是实例化的Vue,main.js那个 new Vue(), 所有的配置都会到这,每个组件都会被处理成一个类似的Vue实例。
至于为什么可以使用this.$http.post,以及this.$router 这样的方法,是因为vue-resource vue-router 把自己的方法注入到了Vue实例里,组件里的this都是一个Vue实例,所以也继承了$http和$router这样的方法。
所以引入插件的时候要使用Vue.use 这个方法有一个工作就是把自己的全局方法注入到Vue里面,让你在每个组件里都能用它们。
012017-11-14 -
testname
2017-11-12
this 指向的是函数运行时的外部环境,这里也就是指组件对象,类似于angular里的 $scope 作用域对象。通过这个 this 就能访问一切定义在组件中的数据。
至于ES6的箭头函数里的 this 的绑定问题,因为ES6的箭头函数没有自己的this,所以当它访问 this 时,其实找到的是外部的 this, 这样 this 指向就被固定化了。
在es5中,在匿名函数里直接调 this 是指向 window 的 ,箭头函数可以很好的避免这一点。
022017-11-13
相似问题