https://cn.vuejs.org/v2/guide...属性与方法
中说不要在实例属性或者回调函数中使用箭头函数,为什么生命周期方法中刚好相反?
<script>
export default{
data: function () {
return {
loading: false,
txt: '123'
}
},
beforeMount(){
setTimeout(() => {
console.log(this)// vue 实例
}, 1000)
setTimeout(function () {
console.log(this)// window
}, 2000)
}
}
</script>
生命周期函数中的this都是指向Vue实例的,如你的代码所示,在函数beforeMount中,如果要在setTimeout依然使用到执行Vue实例的this,那么最好是箭头函数。
在文档中:
vm.$watch('a', newVal => this.myMethod())
本来这样写
vm.$watch('a', function(){this.myMethod()}); //this指向VUe实例
这样使用箭头函数的话,this就指向Vue实例了,而是执行你的上下文中的this。所以特别提示。