getCurrentInstance()详解
通过该实例可访问组件的 props、slots、emit 等上下文信息,但无法直接获取全局 Vue 实例的配置。该 API 仅在组合式 API 中有效,包括。作为组件实例的代理对象,其作用类似于 Vue 2 的。用于获取当前 Vue 组件的实例对象,返回值为。典型使用场景需配合解构获取。
·
getCurrentInstance() 详解
用于获取当前 Vue 组件的实例对象,返回值为 ComponentInternalInstance 类型。该 API 仅在组合式 API 中有效,包括 setup() 函数和 <script setup> 语法糖环境。通过该实例可访问组件的 props、slots、emit 等上下文信息,但无法直接获取全局 Vue 实例的配置。
典型使用场景需配合解构获取 proxy 属性:
const { proxy } = getCurrentInstance()!
proxy 核心功能解析
作为组件实例的代理对象,其作用类似于 Vue 2 的 this 上下文。通过 proxy 可访问以下内容:
- 组件内定义的 data/computed/methods
- 通过
app.config.globalProperties注册的全局方法/属性 - 模板中可访问的所有 API(如
$router)
调用全局方法示例:
proxy?.$loginDialogShow() // 安全调用全局方法
TypeScript 类型处理
由于 getCurrentInstance() 返回类型可能为 null,推荐以下两种类型处理方式:
// 非空断言(需确保在 setup 上下文中)
const { proxy } = getCurrentInstance()!
// 显式类型断言
const instance = getCurrentInstance() as ComponentInternalInstance
注意事项
- 禁止在异步回调中直接使用
getCurrentInstance(),此时实例可能已销毁 - 生产环境构建时,
proxy的部分属性可能被 tree-shaking 移除 - 优先考虑使用
import { useRouter } from 'vue-router'等显式导入替代proxy.$router隐式访问
更多推荐

所有评论(0)