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

相关推荐
还是鼠鼠34 分钟前
图书管理系统 Axios 源码__新增图书
前端·javascript·vscode·ajax·前端框架·node.js·bootstrap
customer081 小时前
【开源免费】基于SpringBoot+Vue.JS体育馆管理系统(JAVA毕业设计)
java·vue.js·spring boot·后端·开源
还是鼠鼠3 小时前
图书管理系统 Axios 源码 __删除图书功能
前端·javascript·vscode·ajax·前端框架·node.js·bootstrap
轻口味4 小时前
Vue.js `Suspense` 和异步组件加载
前端·javascript·vue.js
m0_zj5 小时前
8.[前端开发-CSS]Day08-图形-字体-字体图标-元素定位
前端·css
还是鼠鼠5 小时前
图书管理系统 Axios 源码__编辑图书
前端·javascript·vscode·ajax·前端框架
北极象5 小时前
vue3中el-input无法获得焦点的问题
前端·javascript·vue.js
百度网站快速收录5 小时前
网站快速收录:如何优化网站头部与底部信息?
前端·html·百度快速收录·网站快速收录
Loong_DQX6 小时前
【react+redux】 react使用redux相关内容
前端·react.js·前端框架
GISer_Jing6 小时前
react redux监测值的变化
前端·javascript·react.js