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

相关推荐
一只小阿乐几秒前
vue 改变查询参数的值
前端·javascript·vue.js·路由·router·网文·未花中文网
Mintopia1 分钟前
😎 HTTP/2 中的 HPACK 压缩原理全揭秘
前端·人工智能·aigc
程序员爱钓鱼9 分钟前
Node.js 编程实战:即时聊天应用 —— WebSocket 实现实时通信
前端·后端·node.js
爱迪斯通18 分钟前
Xsens为拳击康复训练带来运动数据支持
前端
2501_9481226321 分钟前
React Native for OpenHarmony 实战:Steam 资讯 App 服务条款实现
javascript·react native·react.js·游戏·ecmascript·harmonyos
奚大野...26 分钟前
uni-app手机端项目touchmove禁止页面上下拉滑动
前端·javascript·uni-app
Object~35 分钟前
4.const和iota
开发语言·前端·javascript
小小小小宇37 分钟前
前端监测界面内存泄漏
前端
掘金安东尼37 分钟前
⏰前端周刊第 448 期(2026年1月4日-1月10日)
前端·面试·github
攀登的牵牛花41 分钟前
前端向架构突围系列 - 工程化(一):JavaScript 演进史与最佳实践
前端·javascript