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

相关推荐
摘星编程4 小时前
React Native + OpenHarmony:ImageSVG图片渲染
javascript·react native·react.js
计算机学姐4 小时前
基于SpringBoot的民宿预定管理系统【三角色+个性化推荐算法+数据可视化统计】
java·vue.js·spring boot·mysql·信息可视化·intellij-idea·推荐算法
会编程的土豆4 小时前
新手前端小细节
前端·css·html·项目
摘星编程4 小时前
OpenHarmony + RN:Text文本书写模式
javascript·react native·react.js
广州华水科技5 小时前
单北斗GNSS在桥梁形变监测中的应用与技术进展分析
前端
我讲个笑话你可别哭啊5 小时前
鸿蒙ArkTS快速入门
前端·ts·arkts·鸿蒙·方舟开发框架
CherryLee_12105 小时前
基于poplar-annotation前端插件封装文本标注组件及使用
前端·文本标注
特立独行的猫a5 小时前
C++轻量级Web框架介绍与对比:Crow与httplib
开发语言·前端·c++·crow·httplib
周航宇JoeZhou5 小时前
JB2-7-HTML
java·前端·容器·html·h5·标签·表单
代码小库5 小时前
【课程作业必备】Web开发技术HTML静态网站模板 - 校园动漫社团主题完整源码
前端·html