在 Vue 3 的 setup 中需用 getCurrentInstance() 获取组件实例,仅限 setup 及组合式钩子内调用;Vue 3.3+ 已废弃 instance.proxy,应优先使用 defineProps、defineEmits、defineExpose 等显式 API。

在 Vue 3 的 setup 函数中,不能直接访问 this,但可以通过 getCurrentInstance() 获取当前组件实例(即代理后的 ComponentInternalInstance),进而访问 proxy、props、emit、slots、exposed 等属性。
✅ 使用 getCurrentInstance 的前提条件
getCurrentInstance() 只能在以下场景中安全调用:
- 组件的
setup()函数内部(包括onBeforeMount等组合式 API 钩子中) - 不能在异步回调(如
setTimeout、Promise.then)、事件处理函数或普通函数作用域中直接调用(此时可能返回null) - 不能在非 setup 环境(如
data、methods选项式 API 中)使用
✅ 正确获取并使用组件实例
在 setup() 中调用 getCurrentInstance(),它返回一个内部实例对象,其 proxy 属性等价于 Vue 2 的 this(但仅在 setup 期间有效):
import { getCurrentInstance } from 'vue'
export default {
setup() {
const instance = getCurrentInstance()
if (instance) {
// ✅ 安全访问 proxy(相当于 this)
console.log(instance.proxy) // ⚠️ 注意:Vue 3.3+ 已废弃 proxy,推荐用其他方式替代
console.log(instance.props)
console.log(instance.emit)
console.log(instance.slots)
console.log(instance.exposed) // 暴露给父组件的方法/属性
}
return {}
}
}
⚠️ 关于 proxy 的重要说明(Vue 3.3+)
从 Vue 3.3 开始,instance.proxy 已被标记为废弃(deprecated),官方不建议依赖它。推荐替代方案:
- 需要访问响应式数据 → 直接在
setup中定义ref/reactive并返回 - 需要触发事件 → 使用
defineEmits声明并调用 - 需要访问插槽 → 使用
useSlots()(需显式引入) - 需要暴露方法给父组件 → 使用
defineExpose({ ... }) - 需要访问 props → 使用
defineProps声明并直接使用
✅ 实用示例:暴露方法 + 访问 emit
import { defineProps, defineEmits, defineExpose, getCurrentInstance } from 'vue'
const props = defineProps(['title'])
const emit = defineEmits(['update:title', 'submit'])
// ✅ 推荐:直接使用 defineExpose,无需 instance
defineExpose({
focusInput() {
console.log('focused')
}
})
// ✅ 若仍需 instance(如动态访问 slots 或内部状态)
const instance = getCurrentInstance()
if (instance) {
console.log('slots:', instance.slots)
console.log('emit fn:', instance.emit) // 同 defineEmits 返回的 emit
}
export default {
name: 'MyInput'
}
不复杂但容易忽略:优先用组合式 API 显式能力(defineProps、defineEmits、defineExpose),只在必要时(如调试、高级集成)才通过 getCurrentInstance() 获取底层实例。


















