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

相关推荐
摘星编程几秒前
当AI开始学会“使用工具“——从ReAct到MCP,大模型如何获得真正的行动力
前端·人工智能·react.js
light blue bird8 分钟前
设备数据变化上传图表数据汇总组件
大数据·前端·信息可视化
2501_9181269115 分钟前
开源祭祖网页index
前端·开源·html
threelab27 分钟前
Three.js 3D 饼图效果 | 三维可视化 / AI 提示词
javascript·人工智能·3d
傻瓜搬砖人1 小时前
SpringMVC的请求
java·前端·javascript·spring
木易 士心1 小时前
为什么 Promise 比 setTimeout 先执行?——JavaScript 事件循环与异步顺序完全指南
开发语言·javascript·ecmascript
爱上好庆祝1 小时前
学习js的第六天(js基础的结束)
开发语言·前端·javascript·学习·ecmascript
yqcoder1 小时前
JS 类型检测双雄:typeof vs instanceof 深度解析
开发语言·javascript·ecmascript
rADu REME1 小时前
SpringBoot + vue 管理系统
vue.js·spring boot·后端
IT_陈寒1 小时前
JavaScript的异步地狱,我差点没爬出来
前端·人工智能·后端