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

相关推荐
前端开发爱好者12 小时前
前端新玩具:Vike 发布!
前端·javascript
今天也是爱大大的一天吖12 小时前
vue2中的.native修饰符和$listeners组件属性
前端·javascript·vue.js
fxshy12 小时前
在 Vue 3 + Vite 项目中使用 Less 实现自适应布局:VW 和 VH 的应用
前端·javascript·less
奇舞精选12 小时前
AI时代的前端知识拾遗:前端事件循环机制详解(基于 WHATWG 最新规范)
前端·javascript
小月鸭12 小时前
理解预处理器(Sass/Less)
前端
AI3D_WebEngineer12 小时前
企业级业务平台项目设计、架构、业务全解之组件库篇
前端·javascript·vue
charlie11451419113 小时前
从零开始理解 CSS:让网页“活”起来的语言2
前端·css·笔记·学习·选择器·样式表·原生
浪裡遊13 小时前
Next.js路由系统
开发语言·前端·javascript·react.js·node.js·js
mapbar_front13 小时前
职场中的顶级能力—服务意识
前端
STUPID MAN13 小时前
Linux使用tomcat发布vue打包的dist或html
linux·vue.js·tomcat·html