大佬教程收集整理的这篇文章主要介绍了为什么在 Vue 3 函数中未定义“this”,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
看看下面 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>
我试图理解当 this
函数从 undefined
函数调用时,为什么 two()
在 one()
函数中是 setup()
。这两个函数都在 this
中返回,因此我希望它们都可以访问 this
。
话虽如此,我如何在我的 two()
函数中获得对 {{1}} 组件实例的引用?
我认为 Vue 仍然必须遵守 Javascript 的规则。调用事件处理程序时,通常是在接收事件的对象的上下文中。在这种情况下,调用 one()
时,this
绑定到 Proxy
元素的 <a>
。
然而,two()
是在没有上下文的情况下专门调用(即:two()
而不是 someobject.foo()
)。这意味着 this
将是未定义的。
我对 Vue 不是很熟悉,但我想它不会进行自动方法绑定,以免要求您为不使用的东西付费。
由于在 this
中正确绑定了 one()
,您实际上可以将 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>
以上是大佬教程为你收集整理的为什么在 Vue 3 函数中未定义“this”全部内容,希望文章能够帮你解决为什么在 Vue 3 函数中未定义“this”所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。