这两个示例都使用arrow函数()=>{}
,该函数绑定this
到与Vue实例不同的上下文。
根据文档:
不要在实例属性或回调(例如vm.$watch('a',newVal=>this.myMethod())
)上使用箭头功能。由于箭头函数绑定到父上下文,因此this
将不会是您期望的Vue实例,并且this.myMethod
将是未定义的。
为了获得对this
Vue实例的正确引用,请使用常规函数:
mounted: function () {
console.log(this);
}
另外,您也可以使用ECMAScript 5速记功能:
mounted() {
console.log(this);
}