看一下 Vue 3 中的以下简单组件示例:
<script>
import { defineComponent } from 'vue'
export default defineComponent({
name: 'Test',
setup(){
return{
one,
two
}
}
})
function one(){
console.log(this) //<-- Proxy{}
two()
}
function two(){
console.log(this) //<-- undefined
}
</script>
<template>
<a href="#" @click.prevent="one()">Start</a>
</template>
我试图理解为什么当从 one( 调用时,
函数。这两个函数都在 this
在 two()
函数中是 未定义
)setup()
中返回,因此我希望它们都可以访问 this
。
话虽如此,我如何在我的 two()
函数中获取对 this
组件实例的引用?
最佳答案
我想 Vue 仍然必须遵守 Javascript 的规则。当事件处理程序被调用时,通常是在接收事件的对象的上下文中。在这种情况下,one()
通过 this
调用绑定(bind)到Proxy
对于<a>
元素。
但是,two()
在没有上下文的情况下专门调用(即: two()
而不是 someobject.foo()
)。这意味着this
将是未定义的。
我对 Vue 不是很熟悉,但我想它不会进行自动方法绑定(bind),以免要求你为不使用的东西付费。
自 this
在 one()
中正确绑定(bind),你实际上可以调用two()
作为 this
的方法而不是作为一个裸函数:
<script>
import { defineComponent } from 'vue'
export default defineComponent({
name: 'Test',
setup(){
return{
one,
two
}
}
})
function one(){
console.log(this) //<-- Proxy{}
this.two()
}
function two(){
console.log(this) //<-- Proxy{}
}
</script>
<template>
<a href="#" @click.prevent="one()">Start</a>
</template>
关于javascript - 为什么 Vue 3 函数中 "this"未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68233918/