在 vue 3 中获取 this 的方法有:使用箭头函数;使用绑定函数;使用 .bind() 方法。

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










