前端 - vue3 - - getCurrentInstance详解以及为什么不推荐使用
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
(图片来源网络,侵删)
(图片来源网络,侵删)
免责声明:我们致力于保护作者版权,注重分享,被刊用文章因无法核实真实出处,未能及时与作者取得联系,或有版权异议的,请联系管理员,我们会立即处理! 部分文章是来自自研大数据AI进行生成,内容摘自(百度百科,百度知道,头条百科,中国民法典,刑法,牛津词典,新华词典,汉语词典,国家院校,科普平台)等数据,内容仅供学习参考,不准确地方联系删除处理! 图片声明:本站部分配图来自人工智能系统AI生成,觅知网授权图片,PxHere摄影无版权图库和百度,360,搜狗等多加搜索引擎自动关键词搜索配图,如有侵权的图片,请第一时间联系我们。