vue3的getCurrentInstance获取组件实例踩坑记录

2024-06-04 9612阅读

一、getCurrentInstance基本用法

我们可以通过 getCurrentInstance这个函数来返回当前组件的实例对象,也就是当前vue这个实例对象

Vue2中,可以通过this来获取当前组件实例;

Vue3中,在setup中无法通过this获取组件实例,console.log(this)打印出来的值是undefined。

在Vue3中,getCurrentInstance()可以用来获取当前组件实例

常见的用途包括:

  1. 访问组件实例的属性:可以通过 getCurrentInstance().ctx 或 getCurrentInstance().proxy 来获取当前组件实例的属性。例如,可以使用 getCurrentInstance().ctx.$props 访问组件的 props 属性。

  2. 调用组件实例的方法:可以通过 getCurrentInstance().ctx 或 getCurrentInstance().proxy 来调用当前组件实例的方法。例如,可以使用 getCurrentInstance().ctx.$emit 来触发组件的自定义事件。

  3. 在生命周期钩子中使用:可以在组件的生命周期钩子中使用 getCurrentInstance() 来获取当前组件实例,以便在钩子函数中访问组件实例的属性或调用组件实例的方法。

请注意,getCurrentInstance 的返回值是一个组件实例对象,可以通过 .ctx 来访问该实例的上下文对象,或者通过 .proxy 来访问该实例的代理对象。两者的区别在于,通过 .ctx 访问的是真实的组件实例,而通过 .proxy 访问的是一个代理对象,该代理对象可以在模板中直接使用。

基本使用:

import { getCurrentInstance, onMounted} from 'vue'
export default {
    setup() {
        onMounted(() => {
            const instance = getCurrentInstance()
            console.log('实例', instance)
        })
        return {}
     }

打印出来的内容如下

vue3的getCurrentInstance获取组件实例踩坑记录 第1张

我们可以根据自己的需求使用当前实例的一些属性和方法,比如我们获取当前组件中某个div的dom

代码如下:

    
import { getCurrentInstance, onMounted} from 'vue' export default { setup() { const refName = 'cxContainer' onMounted(() => { const instance = getCurrentInstance().ctx const dom = instance.$refs[refName] console.log('dom', dom) }) return { refName } }

打印结果如下:

vue3的getCurrentInstance获取组件实例踩坑记录 第2张

可以看到成功的获取了dom

注意:这种获取dom方式不推荐使用,具体见下文

二、getCurrentInstance使用注意点

1. getCurrentInstance 只能在 setup 或生命周期钩子中使用

举个例子:

import { getCurrentInstance, onMounted} from 'vue'
export default {
    setup() {
        const refName = 'cxContainer'
        const onResize = () => {
            const instance = getCurrentInstance()
        	console.log('instance', instance)		
        }
        onMounted(() => {
            window.addEventListener('resize', onResize)
        })
        return {
       		 refName 
        }
     }

以上代码我们将const instance = getCurrentInstance()放在了onResize函数中,然后在onMounted中监听浏览器尺寸变化,尺寸变化就出发onResize函数。

打印结果如下:

vue3的getCurrentInstance获取组件实例踩坑记录 第3张

可以看到instance为null,

这时如果我们将const instance = getCurrentInstance()放到setup函数中,或者onMounted中就可以成功获取实例

如需在 setup或生命周期钩子外使用,先在 setup 中调用 getCurrentInstance() 获取该实例然后再使用。

2. getCurrentInstance线上环境报错问题

本地代码

    import {getCurrentInstance} from "vue";
    export default {
      setup() {
         const {ctx} = getCurrentInstance();
         console.log('ctx', ctx)
      }
    

以上代码在本地开发调试没有问题,在线上环境会报错,如果通过这个ctx.$refs[xxx]获取dom,线上就会有问题。

解决方案

使用proxy代替ctx,proxy线上不会出现问题

const { proxy } = getCurrentInstance()  

三、在vue3中不推荐使用getCurrentInstance获取组件实例

大家可以看看这位大佬的记录vue3中getCurrentInstance不推荐使用以及在<script setup>中获取全局内容(三种方式)

官方解释:

主要还是 getCurrentInstance 是一个内部的API,并不是公开的API,使用内部API去实现一些业务功能,可能会因为后续 Vue 的版本迭代而造成业务上的 BUG。并且 Vue3 的 Composition API 强调的就是业务的解耦和复用性,依赖组件实例属性并不是一个很好的开发方式。而 vue 相关生态的使用其实就是他们内部的事情了,他们有完善的测试用例可以跑测试,但是我们并没有,如果后续的某一个版本Vue变更了这个API,那么如果没有经过完整测试就部署上去的项目就会出现大规模的BUG反馈了

vue3的getCurrentInstance获取组件实例踩坑记录 第4张

如果是获取dom大家可以通过ref获取,比如:

     
hhhhhh
import {ref,onMounted } from 'vue' export default { setup() { const test = ref(null) onMounted(() => { console.log('test实例',test.value) }) return { test } }

打印结果如下:

vue3的getCurrentInstance获取组件实例踩坑记录 第5张

至于其他的一些常用属性和方法,vue3中的setup中提供了props和contexts上下文。官方setup用法

props

vue3的getCurrentInstance获取组件实例踩坑记录 第6张

context

vue3的getCurrentInstance获取组件实例踩坑记录 第7张


    免责声明:我们致力于保护作者版权,注重分享,被刊用文章因无法核实真实出处,未能及时与作者取得联系,或有版权异议的,请联系管理员,我们会立即处理! 部分文章是来自自研大数据AI进行生成,内容摘自(百度百科,百度知道,头条百科,中国民法典,刑法,牛津词典,新华词典,汉语词典,国家院校,科普平台)等数据,内容仅供学习参考,不准确地方联系删除处理! 图片声明:本站部分配图来自人工智能系统AI生成,觅知网授权图片,PxHere摄影无版权图库和百度,360,搜狗等多加搜索引擎自动关键词搜索配图,如有侵权的图片,请第一时间联系我们,邮箱:ciyunidc@ciyunshuju.com。本站只作为美观性配图使用,无任何非法侵犯第三方意图,一切解释权归图片著作权方,本站不承担任何责任。如有恶意碰瓷者,必当奉陪到底严惩不贷!

    目录[+]