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

注意事项

  1. 禁止在异步回调中直接使用 getCurrentInstance(),此时实例可能已销毁
  2. 生产环境构建时,proxy 的部分属性可能被 tree-shaking 移除
  3. 优先考虑使用 import { useRouter } from 'vue-router' 等显式导入替代 proxy.$router 隐式访问
Logo

电影级数字人,免显卡端渲染SDK,十行代码即可调用,工业级demo免费开源下载!

更多推荐