vue3中 getCurrentInstance
在vue2版本中,可以通过 this 来获取当前组件实例,但是在 vue3 setup 中是无法通过 this 获取组件实例对象。getCurrentInstance()
是在vue3中用于获取当前组件实例的内部 API,主要在组合式 API(Composition API)的 setup()
函数中使用。它可以访问组件的上下文、属性、插槽等。
基本用法
import { getCurrentInstance } from 'vue';export default {setup() {// 获取当前组件实例const instance = getCurrentInstance();// 访问组件上下文console.log(instance); // 包含 proxy、ctx、props 等属性// 通过 proxy 访问组件实例(类似 this)const { proxy } = instance;console.log(proxy.$el); // 根 DOM 元素console.log(proxy.$router); // 路由(若使用 Vue Router)console.log(proxy.$store); // Vuex 状态(若使用 Vuex)return {};}
};
关键属性说明
proxy
当前组件实例的代理对象(最常用),相当于 Vue 2 中的
this
可访问:
$props
,$emit
,$slots
,$el
,$parent
,$root
等注意:仅在开发/生产模式下可用,SSR 中可能受限
ctx
原始上下文(不建议直接使用),与
proxy
类似但不包含 Vue 3 的警告信息兼容性:主要用于兼容旧版库
props
直接访问组件的
props
数据
const { props } = getCurrentInstance(); console.log(props.myProp);
使用场景
访问全局属性
例如获取挂载在app.config.globalProperties
上的全局对象:// main.js app.config.globalProperties.$api = axios;// 组件内 const { proxy } = getCurrentInstance(); proxy.$api.get('/data');
手动触发事件
const { proxy } = getCurrentInstance(); proxy.$emit('custom-event', data);
访问插槽内容
const { slots } = getCurrentInstance(); console.log(slots.default()); // 默认插槽内容
重要注意事项
仅限
setup()
内部使用getCurrentInstance()
必须在setup()
或生命周期钩子中调用,不可在异步函数(如setTimeout
)中直接使用,否则会返回null
。避免滥用
Vue 官方不推荐在业务代码中过度依赖此 API,优先使用标准 Composition API(如props
,emit
,provide/inject
等)。TypeScript 类型支持
为proxy
添加类型:import { ComponentInternalInstance } from 'vue';const instance = getCurrentInstance() as ComponentInternalInstance; const proxy = instance.proxy as { $myProperty: string }; console.log(proxy.$myProperty);
SSR 兼容性
在服务端渲染时,某些属性(如$el
)不可用,需做环境判断。
替代方案(推荐)
访问
props
: 使用defineProps
触发事件: 使用
defineEmits
暴露属性: 使用
defineExpose
依赖注入: 使用
provide/inject
// 更安全的替代方式
import { defineProps, defineEmits } from 'vue';const props = defineProps(['myProp']);
const emit = defineEmits(['custom-event']);emit('custom-event', data); // 无需 getCurrentInstance()