javascript - 为什么 Vue 3 函数中 "this"未定义

标签 javascript vue.js vuejs3

看一下 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( 调用时,thistwo() 函数中是 未定义 ) 函数。这两个函数都在 setup() 中返回,因此我希望它们都可以访问 this

话虽如此,我如何在我的 two() 函数中获取对 this 组件实例的引用?

最佳答案

我想 Vue 仍然必须遵守 Javascript 的规则。当事件处理程序被调用时,通常是在接收事件的对象的上下文中。在这种情况下,one()通过 this 调用绑定(bind)到Proxy对于<a>元素。

但是,two()在没有上下文的情况下专门调用(即: two() 而不是 someobject.foo() )。这意味着this将是未定义的。

我对 Vue 不是很熟悉,但我想它不会进行自动方法绑定(bind),以免要求你为不使用的东西付费。

thisone() 中正确绑定(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/

相关文章:

vue.js - 如何使用 createElement 创建槽的副本?

javascript - 存储在 firebase 服务器中的数组有时会将其元素设置为未定义

javascript - 检测字符串中的数字 - javascript regex

javascript - 使用 setDate 添加天数后,月份没有变化

firebase - Vue + Pinia + Firebase 身份验证 : Fetch currentUser before Route Guard

object - 如何查看对象数组中的特定属性

javascript - 在列表菜单项上切换事件类 - vue js

vue.js - VueJS 对 v-for 中的每个项目进行 API 调用并将它们返回到正确的位置

vuex - 如何将 Vuex mapGetters 与 Vue 3 SFC 脚本设置语法一起使用?

javascript - Nodejs .ini 文件标题