VueJS:为什么“这个”未定义? [英] VueJS: why is "this" undefined?
问题描述
我正在使用 Vue.js 创建一个组件。
I'm creating a component with Vue.js.
当我在任何此时v2 / api /#Options-Lifecycle-Hooksrel =noreferrer>生命周期钩子(创建
,已挂载
,更新
等)它评估为 undefined
:
When I reference this
in any of the the lifecycle hooks (created
, mounted
, updated
, etc.) it evaluates to undefined
:
mounted: () => {
console.log(this); // logs "undefined"
},
同样的事情也发生在我的计算属性中:
The same thing is also happening inside my computed properties:
computed: {
foo: () => {
return this.bar + 1;
}
}
我收到以下错误:
Uncaught TypeError:无法读取未定义的属性'bar'
Uncaught TypeError: Cannot read property 'bar' of undefined
为什么此
在这些情况下评估为 undefined
?
Why is this
evaluating to undefined
in these cases?
推荐答案
这两个例子都使用箭头功能 ()=> {}
,它将此
绑定到与Vue实例不同的上下文。
Both of those examples use an arrow function () => { }
, which binds this
to a context different from the Vue instance.
根据文档:
不要在实例属性或回调中使用箭头函数(例如
vm。$ watch('a',newVal => this.myMethod ())
)。由于箭头函数绑定到父上下文,此
将不是您期望的Vue实例,而this.myMethod
将是未定义的。
Don’t use arrow functions on an instance property or callback (e.g.
vm.$watch('a', newVal => this.myMethod())
). As arrow functions are bound to the parent context,this
will not be the Vue instance as you’d expect andthis.myMethod
will be undefined.
为了获得对的正确引用,这个
作为Vue实例,使用常规函数:
In order to get the correct reference to this
as the Vue instance, use a regular function:
mounted: function () {
console.log(this);
}
或者,您也可以使用 ECMAScript 5简写:
mounted() {
console.log(this);
}
这篇关于VueJS:为什么“这个”未定义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!