在 <script setup> 中获取组件实例需调用 getCurrentInstance(),仅限顶层同步代码、组合式生命周期钩子及自定义 Hook 内使用;异步回调等场景返回 null,且 Vue 3.3+ 应避免 instance.proxy。

在 <script setup> 中获取当前组件实例,需调用 getCurrentInstance(),但它有明确的使用边界和替代建议——不是所有场景都推荐用,尤其 Vue 3.3+ 后更应避免依赖 instance.proxy。
只能在 setup 作用域内安全调用
getCurrentInstance() 返回值为 ComponentInternalInstance | null,仅在以下位置有效:
-
<script setup>的顶层同步代码中(最常用) - 组合式生命周期钩子内,如
onMounted、onBeforeUnmount - 自定义 Hook 内部(前提是该 Hook 被 setup 调用)
⚠️ 在异步回调(setTimeout、Promise.then)、普通函数、事件处理函数或模板表达式中直接调用,大概率返回 null。
获取后怎么访问常用功能
拿到实例后,可按需访问其属性,但要注意 Vue 版本差异:
立即学习“前端免费学习笔记(深入)”;
-
instance.props—— 直接读取已声明的 props(推荐,无需 proxy) -
instance.emit—— 触发事件,前提是已用defineEmits声明 -
instance.slots—— 访问插槽对象,也可用useSlots()替代 -
instance.exposed—— 父组件通过 ref 调用子组件方法时,子组件需用defineExpose({})显式暴露 -
instance.refs—— 获取绑定 ref 的 DOM 或子组件实例(如<div ref="box"></div>)
❌ instance.proxy 在 Vue 3.3+ 已废弃,控制台会警告,不应再用于访问 $props、$emit 等。
实际写法示例(<script setup>)
以下是一个完整、现代、无警告的写法:
import { getCurrentInstance, onMounted, ref } from 'vue'
const box = ref(null)
const instance = getCurrentInstance()
onMounted(() => {
console.log('props:', instance?.props)
console.log('refs:', instance?.refs.box) // 等价于 box.value
})
// 暴露给父组件的方法
defineExpose({
focus: () => box.value?.focus()
})
注意:不需要解构 proxy,也不需要类型断言(如 as ComponentInternalInstance),加可选链 ? 即可安全访问。
什么情况下不该用 getCurrentInstance
多数日常需求已有更清晰、更稳定的替代方式:
- 想读 props → 直接用
defineProps()声明并访问变量 - 想发事件 → 用
defineEmits()声明后调用返回的函数 - 想操作 DOM → 用
ref绑定 +onMounted访问 - 想让父组件调子方法 →
defineExpose()+ 父组件ref调用
只有在极少数需要底层上下文(如封装高级 Hook、调试、集成第三方库)时,才考虑用 getCurrentInstance,且务必检查返回值是否为 null。


















