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

例子:

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

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

我在点击某个按钮的时候,调用了方法handler,传递了一个参数是字符串 'condition',然后方法中通过 this.$refs[strRef] 后去到绑定 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.refs[strRef] 的方法获取到相关的组件实例

相关推荐
Hello--_--World几秒前
ES15:Object.groupBy() 和 Map.groupBy()、Promise.withResolvers() 相关知识点
开发语言·前端·javascript
一 乐3 分钟前
房产租赁管理|基于springboot + vue房产租赁管理系统(源码+数据库+文档)
java·数据库·vue.js·spring boot·论文·毕设·房产租赁管理系统
Cache技术分享9 分钟前
386. Java IO API - 监控目录变化
前端·后端
Hooray16 分钟前
管理后台框架 AI 时代的版本答案,Fantastic-admin 6.0 它来了!
前端·前端框架·ai编程
2501_9136800024 分钟前
Vue3项目快速接入AI助手的终极方案 - 让你的应用智能升级
前端·vue.js·人工智能·ai·vue·开源软件
开开心心_Every26 分钟前
动图制作工具,拆分转视频动态照离线免费
运维·前端·人工智能·edge·pdf·散列表·启发式算法
饭后一颗花生米34 分钟前
2026 前端实战:AI 驱动下的性能优化与工程化升级
前端·人工智能·性能优化
YJlio41 分钟前
4月14日热点新闻解读:从金融数据到平台治理,一文看懂今天最值得关注的6个信号
java·前端·人工智能·金融·eclipse·电脑·eixv3
xjf771143 分钟前
AI重构前端项目指南
前端·ai·重构·编程
踩着两条虫1 小时前
VTJ:应用场景展示
前端·vue.js·架构