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

相关推荐
用户6802659051191 天前
2025年十大终端管理软件推荐指南
vue.js·后端·面试
孜孜不倦不忘初心1 天前
Axios 常用配置及使用
前端·axios
sTone873751 天前
vscode 二开踩坑记录
前端
用户8168694747251 天前
Effect 执行时机与事件循环交错关系
前端·react.js
心在飞扬1 天前
langchain学习总结-OutputParser组件及使用技巧
前端·后端
llq_3501 天前
Ant Design v5 样式兼容性问题与解决方案
前端
triumph_passion1 天前
React Hook Form 状态下沉最佳实践
前端·react.js
心在飞扬1 天前
langchain学习总结-两个Runnable核心类的讲解与使用
前端·后端
德育处主任1 天前
在小程序做海报的话,Painter就很给力
前端·微信小程序·canvas
匠心码员1 天前
Git Commit 提交规范:让每一次提交都清晰可读
前端