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

相关推荐
一只小风华~6 分钟前
Vue Router 路由元信息(meta)详解
前端·javascript·vue.js
*且听风吟36 分钟前
html 实现鼠标滑动点亮横轴
前端·javascript·html
计算机学姐39 分钟前
基于微信小程序的垃圾分类管理系统【2026最新】
java·vue.js·spring boot·mysql·微信小程序·小程序·mybatis
武昌库里写JAVA2 小时前
C语言 #pragma once - C语言零基础入门教程
vue.js·spring boot·sql·layui·课程设计
iCoding912 小时前
前端分页 vs 后端分页:技术选型
前端·后端·系统架构
mingtianyihou332 小时前
使用 Service Worker 限制请求并发数
前端
张可爱2 小时前
20251017-Vue2八股文整理(上篇)
前端
FanetheDivine2 小时前
ts中如何描述一个复杂函数的类型
前端·typescript
lightgis2 小时前
chrome中的axure插件提示无法不受支持
前端·chrome
速易达网络3 小时前
Vue3 原生移动应用开发来了
前端·javascript·css