vue3怎么根据字符串获取组件实例

例子:

我在使用vue2开发的时候,定义了一个方法

复制代码
handler(strRef){ this.$refs[strRef].innerText = 'hello world' },

我在点击某个按钮的时候,调用了方法handler,传递了一个参数是字符串 'condition',然后方法中通过 this.$refsstrRef 后去到绑定 ref = 'condition' 的组件,我在vue3中也需要通过这样的方法获取到相关组件

我们可以通过

复制代码
import { getCurrentInstance } from 'vue'

const instance: any = getCurrentInstance()

获取到当前的组件实例,其中 instance 就是当前组件实例,

组件代码:

复制代码
<script setup lang="ts">
import { ref, onMounted, getCurrentInstance } from 'vue'

const instance: any = getCurrentInstance()

const xxx = ref('hello world')
const xxxInstance = ref(null)

onMounted(() => {
  console.log(instance, 'instance')
})
</script>
<template>
  <h1 ref="xxxInstance">{{ xxx }}</h1>
</template>

<style lang="less" scoped></style>

下面我们来输出一下,看看 instance 下面都有什么

可以看到 instance 下面存在 refs 对象,其中存在的就是绑定的各个组件实例

所以当 strRef 是字符串变量时,我们可以通过 instance.refsstrRef 的方法获取到相关的组件实例

相关推荐
乌鲁木齐德润恒圣信息科技有限公司39 分钟前
GEO生成式引擎优化:技术原理与43引擎自动测试系统
大数据·前端·人工智能
泯泷1 小时前
第一章:Lit简介 - 现代Web组件标准
前端·javascript·web components
Moment1 小时前
AI 写代码越来越快,程序员为什么反而更累了
前端·后端·面试
apeman2 小时前
git-cherry合并代码工具
前端·后端
SGAMERrain2 小时前
前端小游戏有 25000+ 答案,如何避免一次性加载全部数据?
前端
kyriewen3 小时前
我让用户白等两秒,只为一个 16MB 的中文字体
前端·javascript·程序员
一只程序布3 小时前
Day 21|前端转全栈第 21 天:不用写 XML 了,配置只剩一个 yml
前端
小小小小宇3 小时前
固定使用 Chrome 135 启动 CDP
前端
小小小小宇4 小时前
Chrome 136后 CDP 协议 该如何使用
前端
王晋1574 小时前
从 Thunderbird 到 Betterbird:银河麒麟 ARM64 邮件客户端迁移实录
前端