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

相关推荐
技术净胜26 分钟前
Python 操作 Cookie 完全指南,爬虫与 Web 开发实战
前端·爬虫·python
神奇的程序员28 分钟前
Nginx日志分析工具-NginxPulse开源了
前端
我是小疯子6642 分钟前
前端开发入门:HTML、CSS与JS学习指南
前端
知了清语1 小时前
是的,微信小程序的 show-menu-by-longpress 真的会让你无语
前端
Hao_Harrision1 小时前
50天50个小项目 (React19 + Tailwindcss V4) ✨| RangeSlider(范围滑块组件)
前端·typescript·react·tailwindcss·vite7
CC码码1 小时前
不修改DOM的高亮黑科技,你可能还不知道
前端·javascript·面试
虚诚1 小时前
vue2中树形表格怎么实现
前端·javascript·vue.js·ecmascript·vue2·树形结构
wuhen_n1 小时前
Promise与async/await
前端