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

相关推荐
ヤ鬧鬧o.4 分钟前
多彩背景切换演示
前端·css·html·html5
一起养小猫12 分钟前
Flutter实战:从零实现俄罗斯方块(三)交互控制与事件处理
javascript·flutter·交互
lethelyh18 分钟前
Vue day1
前端·javascript·vue.js
酉鬼女又兒23 分钟前
SQL113+114 更新记录(一)(二)+更新数据知识总结
java·服务器·前端
无风听海23 分钟前
AngularJS中 then catch finally 的语义、执行规则与推荐写法
前端·javascript·angular.js
利刃大大40 分钟前
【Vue】组件化 && 组件的注册 && App.vue
前端·javascript·vue.js
Whisper_Sy1 小时前
Flutter for OpenHarmony移动数据使用监管助手App实战 - 周报告实现
开发语言·javascript·网络·flutter·php
Anastasiozzzz1 小时前
leetcodehot100--最小栈 MinStack
java·javascript·算法
一起养小猫1 小时前
Flutter for OpenHarmony 实战:按钮类 Widget 完全指南
前端·javascript·flutter
css趣多多1 小时前
Vux store实例的模块化管理
前端