**组件方法中的
this
**:1
2
3
4
5methods: {
greet() {
console.log(`Hello, ${this.name}!`); // this 指向组件实例
}
}this
指向:组件实例。
**箭头函数中的
this
**:1
2
3
4
5methods: {
greet: () => {
console.log(`Hello, ${this.name}!`); // this 不指向组件实例,指向定义时的上下文(通常是 window)
};
}this
指向:定义箭头函数时的上下文,通常在非模块化代码中是window
。
**生命周期钩子中的
this
**:1
2
3created() {
console.log(this); // this 指向 Vue 实例
}this
指向:Vue 实例。
**事件处理器中的
this
**:1
<button @click="handleClick">Click me</button>
1
2
3
4
5methods: {
handleClick() {
console.log(this); // this 指向组件实例
}
}this
指向:组件实例。
**回调函数中的
this
**:1
2
3
4
5
6
7
8
9
10
11
12methods: {
later() {
setTimeout(function() {
console.log(this); // this 指向 window 或 undefined(严格模式下)
}, 1000);
},
laterArrow() {
setTimeout(() => {
console.log(this); // this 指向组件实例
}, 1000);
}
}later
方法中的this
指向:window
对象(在非严格模式下)或undefined
(在严格模式下)。laterArrow
方法中的this
指向:组件实例。
使用
bind
方法:1
2
3
4
5
6
7methods: {
greet() {
setTimeout(() => {
console.log(this); // this 指向 window 或 undefined
}.bind(this), 1000); // 使用 .bind 使 this 指向组件实例
}
}setTimeout
回调中的this
指向:组件实例,因为使用了.bind(this)
。
保存
this
引用:1
2
3
4
5
6
7
8methods: {
greet() {
const self = this; // 保存 this 引用
setTimeout(function() {
console.log(self); // self 指向组件实例
}, 1000);
}
}setTimeout
回调中的self
指向:组件实例。
在 Vue 组件中,通常我们希望 this
指向当前组件实例,以便可以访问组件的数据和方法。箭头函数和 .bind
方法的使用会影响 this
的指向,因此在编写代码时需要特别注意。