vue3怎么根据字符串获取组件实例

例子:

我在使用vue2开发的时候,定义了一个方法

复制代码
handler(strRef){ this.$refs[strRef].innerText = 'hello world' },

我在点击某个按钮的时候,调用了方法handler,传递了一个参数是字符串 'condition',然后方法中通过 this.$refsstrRef 后去到绑定 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.refsstrRef 的方法获取到相关的组件实例

相关推荐
绺年几秒前
模块化加载机制与循环依赖的探索
前端
Csvn9 分钟前
前端技术 - 前端技术债务
前端
Days205019 分钟前
Flyfish Viewer:全能纯前端多格式文件预览组件,解锁浏览器端无门槛预览新体验
前端
selfsuer20 分钟前
【奇奇怪怪前端问题记录】
前端
不要额外加糖23 分钟前
给 Codex 戴上紧箍, 治一治 AI 的过度发挥
前端·人工智能·代码规范
吃阿茶搽42 分钟前
源码剖析:Standard组件架构与底层实现原理
javascript
卤蛋fg644 分钟前
给 vxe-table 设置全局默认参数:setConfig、setIcon 与 setTheme
vue.js
文心快码BaiduComate44 分钟前
Comate搭载MiniMax M3:支持超长百万上下文
前端·人工智能·后端
浩风祭月44 分钟前
React 18 并发特性实战:用 useTransition 和 useDeferredValue 优化列表搜索体验
前端·react native