在 vue 3 中获取 this 的方法有:使用箭头函数;使用绑定函数;使用 .bind() 方法。
如何在 Vue 3 中获取 this
在 Vue 3 中,可以通过以下方法获取 this:
1. 使用箭头函数
const myComponent = {
template: '<div></div>',
methods: {
logThis: () => {
console.log(this); // this 指向该组件实例
},
},
};
2. 使用绑定函数
立即学习“前端免费学习笔记(深入)”;
const myComponent = {
template: '<div></div>',
methods: {
logThis() {
console.log(this); // this 指向该组件实例
},
},
};
3. 使用 .bind() 方法
const myComponent = {
template: '<div></div>',
methods: {
logThis() {
console.log(this); // this 指向该组件实例
},
},
mounted() {
this.$el.addEventListener('click', this.logThis.bind(this));
},
};
注意:
- 在使用箭头函数时,请确保箭头函数内部没有改变 this 的引用。
- 在使用绑定函数时,请确保绑定的是 this.logThis 方法,而不是 this.logThis() 方法。
- 在使用 .bind() 方法时,请确保在组件挂载后才添加事件监听器。