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

相关推荐
charlie1145141914 分钟前
前端三件套简单学习:HTML篇1
开发语言·前端·学习·html
很多石头5 分钟前
前端img与background-image渲染图片对H5页面性能的影响
前端·css
yenggd5 分钟前
3种XSS攻击简单案例
前端·xss
盖头盖7 分钟前
【xss基本介绍】
前端·xss
一枚前端小能手14 分钟前
「周更第2期」实用JS库推荐:Rsbuild
前端·javascript
小桥风满袖14 分钟前
极简三分钟ES6 - 正则表达式的扩展
前端·javascript
柯南二号20 分钟前
【大前端】React 使用 Redux 实现组件通信的 Demo 示例
前端·javascript·react.js
学习3人组20 分钟前
React JSX 语法讲解
前端·react.js·前端框架
小高00725 分钟前
🚨 2025 最该淘汰的 10 个前端 API!
前端·javascript·面试
一枚前端小能手27 分钟前
🎨 页面卡得像PPT?浏览器渲染原理告诉你性能瓶颈在哪
前端·javascript