getCurrentInstance可返回但前组件的内部实例 我们可以从proxy中拿到挂载到vue实例中的属性
//main.ts
app.config.globalProperties.$fn = () => {
console.log('我是全局挂载属性')
}
// index.vue
const {proxy} = getCurrentInstance()!
proxy?.$fn()
我们可能会认为这个proxy就等同于vue2中的this 实则不然 结合getCurrentInstance()后面的!讲解一下:
1、为什么要加!
getCurrentInstance的类型是这么定义的
interface ComponentInternalInstance {
uid: number
type: Component
parent: ComponentInternalInstance | null
root: ComponentInternalInstance
appContext: AppContext
props: Data
attrs: Data
slots: Slots
emit: EmitFn
// ...其他内部属性
}
function getCurrentInstance(): ComponentInternalInstance | null;
!是ts中做非空判断使用的 此处意义为 只有当getCUrrentInstance为ComponentInternalInstance时才会执行 所以下面的proxy后面用可选链操作符?. 对proxy做了非空判断
2、为什么getCurrentInstance类型定义可能为null呢
因为setup语法糖是在beforeCreate前执行的 此时可能无法获取到vue实例 所以定义类型可能为null
3、为什么不推荐使用
鱿鱼原话:直接访问实例会绕过vue3的响应式系统 不符合vue3的中心思想(解耦和复用性),getCurrentInstance已经在最新的文档说明中移除 是因为它作为一个内部api 不应该被公开使用 只会用于vue3生态中某些测试库
说白了 就是getCurrentInstance这个api只想给他们内部人员用于调试使用 后期随着版本的迭代维护 可能会对getCurrentInstance做改动 因其属于ComponentInternalInstance接口 此接口中包含了许多属性 万一改动的话 很多项目会出现大量bug 所以不推荐开发者使用 所以大家在调试某些功能的时候可以使用 回归到正常的功能开发就不要用了 推荐大家改用provide和inject