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

相关推荐
小帅说java11 小时前
【Spring开发】SpringCloud服务端基础框架第9篇:3.Gateway服务网关【附代码文档】
javascript·spring
布列瑟农的星空11 小时前
重学React——memo能防止Context的额外渲染吗
前端
FuckPatience11 小时前
Vue 与.Net Core WebApi交互时路由初探
前端·javascript·vue.js
小小前端_我自坚强11 小时前
前端踩坑指南 - 避免这些常见陷阱
前端·程序员·代码规范
lichenyang45311 小时前
从零实现JSON与图片文件上传功能
前端
WebGirl11 小时前
动态生成多层表头表格算法
前端·javascript
hywel12 小时前
一开始只是想整理下书签,结果做成了一个 AI 插件 😂
前端
傅里叶12 小时前
SchedulerBinding 的三个Frame回调
前端·flutter
小小前端_我自坚强12 小时前
React Hooks 使用详解
前端·react.js·redux
java水泥工12 小时前
基于Echarts+HTML5可视化数据大屏展示-车辆综合管控平台
前端·echarts·html5·大屏模版