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 分钟前
Android Framework在mk中新增类似PRODUCT_MODEL的变量并传递给buildinfo.sh及prop属性中
android·linux·前端
她超甜i37 分钟前
css省略号展示,兼容性强,js判断几行,不需要定位
javascript·css·vue.js
小码吃趴菜1 小时前
【无标题】
前端·chrome
毕设源码-朱学姐2 小时前
【开题答辩全过程】以 基于HTML5的购物网站的设计与实现为例,包含答辩的问题和答案
前端·html·html5
梦6502 小时前
CSS 元素垂直水平居中的 8 种方法
前端·css
We་ct2 小时前
LeetCode 68. 文本左右对齐:贪心算法的两种实现与深度解析
前端·算法·leetcode·typescript
ShoreKiten2 小时前
ctfshow-web316
运维·服务器·前端
前端 贾公子2 小时前
release-it 使用指南
前端·javascript
全栈技术负责人3 小时前
前端团队 AI Core Workflow:从心法到落地
前端·人工智能·状态模式
前端 贾公子3 小时前
深入浅出 CSS 属性:pointer-events: none
前端·css