You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue3中setup返回的函数调用时this为undefined的原因及解决方案

问题原因
  1. Vue 3 模板中调用事件回调方法时,会自动将方法的this绑定为当前组件实例,因此模板触发one()时,one内部的this指向组件Proxy对象。
  2. setup 函数本身没有this上下文,你返回的one、two只有在被模板调用时才会获得Vue绑定的this,普通场景下调用不会自动绑定上下文。你在one中直接调用two()属于严格模式下的普通函数调用,因此two内部的this为undefined(Vue SFC默认开启严格模式)。
解决方案

下面是两种常用的实现方式:

方案1:手动绑定执行上下文

在one中调用two时,用call/apply将one的this绑定给two即可:

<script>
import { defineComponent } from 'vue'

export default defineComponent({
  name: 'Test',
  setup(){
    return{
      one,
      two
    }
  }
})

function one(){
  console.log(this) //<-- Proxy{}
  two.call(this) // 手动绑定this上下文
}

function two(){
  console.log(this) //<-- 现在指向组件实例Proxy
}
</script>
  
<template>
  <a href="#" @click.prevent="one()">Start</a>
</template>

方案2:使用getCurrentInstanceAPI获取实例

不需要依赖this,直接通过Vue提供的getCurrentInstance方法在同步执行的函数中获取当前组件实例:

<script>
import { defineComponent, getCurrentInstance } from 'vue'

export default defineComponent({
  name: 'Test',
  setup(){
    return{
      one,
      two
    }
  }
})

function one(){
  console.log(this) //<-- Proxy{}
  two()
}

function two(){
  const instance = getCurrentInstance()
  console.log(instance) //<-- 当前组件实例
}
</script>
  
<template>
  <a href="#" @click.prevent="one()">Start</a>
</template>

注意:getCurrentInstance 仅可在 setup、生命周期钩子、同步执行的函数中调用,如果是异步场景需要提前在同步阶段把实例存下来再使用。

内容的提问来源于stack exchange,提问作者Clifton Labrum

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.14 02:36:02