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

相关推荐
Hilaku5 分钟前
深入background-image:你可能不知道的几个性能优化与高级技巧
前端·css
南岸月明7 分钟前
副业自媒体1年终于明白:为什么会表达的人,能量越来越强,更能赚到钱?
前端
Danny_FD21 分钟前
Vue + Element UI 实现模糊搜索自动补全
前端·javascript
gnip26 分钟前
闭包实现一个简单Vue3的状态管理
前端·javascript
斐济岛上有一只斐济31 分钟前
后端程序员的CSS复习
前端
Enddme34 分钟前
《面试必问!JavaScript 中this 全方位避坑指南 (含高频题解析)》
前端·javascript·面试
有梦想的程序员36 分钟前
微信小程序使用 Tailwind CSS version 3
前端
wocwin1 小时前
Vue移动端项目二次封装原生table组件,支持表头/数据动态配置(支持多级表头、排序);作用域插槽、render函数渲染某列数据等功能
vue.js
你怎么知道我是队长1 小时前
python---eval函数
开发语言·javascript·python
溟洵1 小时前
Qt 窗口 工具栏QToolBar、状态栏StatusBar
开发语言·前端·数据库·c++·后端·qt