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 的方法获取到相关的组件实例

相关推荐
不听话坏16 小时前
Ignition篇(下 一) 动态执行前的事情
开发语言·前端·javascript
likeyi0716 小时前
require 和 import的区别
开发语言·前端
pany16 小时前
做 AI 友好的开源 Vue3 模板 🌈
前端·vue.js·ai编程
小二·17 小时前
React 19 + Next.js 15 现代前端开发实战:App Router / Server Components / 流式渲染
前端·javascript·react.js
daols8817 小时前
vue 甘特图 vxe-gantt 小时视图设置日期轴每间隔 3 个小时
vue.js·甘特图·vxe-gantt
谙忆102418 小时前
前端图片直传对象存储:OSS/S3 预签名 URL、STS 临时凭证与回调校验
前端
CHNE_TAO_EMSM19 小时前
Android studio 打开文件时自动下载源码
前端·javascript·android studio
一孤程20 小时前
Airtest自动化测试第五篇:小程序与Web测试——跨平台自动化全覆盖
前端·自动化测试·小程序·自动化·测试·airtest
IT_陈寒20 小时前
SpringBoot自动配置不是你以为的那样的智能
前端·人工智能·后端
yume_sibai21 小时前
大屏数据可视化 - 边框红绿呼吸灯实现详解
前端·信息可视化·typescript