当前位置: 首页 > news >正文

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

http://www.lryc.cn/news/488432.html

相关文章:

  • ISUP协议视频平台EasyCVR私有化视频平台新能源汽车充电停车管理方案的创新与实践
  • 智领未来: 宏集物联网HMI驱动食品与包装行业迈向智能化新高度
  • redis-击穿、穿透、雪崩
  • 【Redis】服务器异常重启,导致redis启动失败
  • Springboot+Vue的项目搭建(三)
  • 【Word】一键批量引用论文上标——将正文字体改为上标格式
  • DAY1 网络编程(TCP客户端服务器)
  • 如何在Ubuntu当中利用CloudCompare软件进行点云配准拼接?
  • AWTK 最新动态:支持鸿蒙系统(HarmonyOS Next)
  • vue数据变化但页面不变
  • Leetcode128. 最长连续序列(HOT100)
  • 【阅读笔记】Dense trajectories and motion boundary descriptors for action recognition
  • React 远程仓库拉取项目部署,无法部署问题
  • CSS3新特性——字体图标、2D、3D变换、过渡、动画、多列布局
  • 前端反向代理的配置和實現
  • 【K8S系列】Kubernetes Pod节点ImagePullBackOff 状态及解决方案详解【已解决】
  • JSONObject jsonObject = JSON.parseObject(json);
  • 软件测试之测试用例扩展
  • hj 212 协议解包php解包,
  • 03架构模式(D2_架构模式01)
  • 深入List集合:ArrayList与LinkedList的底层逻辑与区别
  • mac安装appuim
  • Telegram bot Mini-App开发实践---Telegram简单介绍与初始化小程序获取window.Telegram.WebApp对象并解析
  • 绿光一字线激光模组:工业制造与科技创新的得力助手
  • 鸿蒙进阶篇-Math、Date
  • 定时器简介
  • 3C产品说明书电子化转变:用户体验、环保与商业机遇的共赢
  • redis:主从复制
  • 思考Redis的用途 2024-11-19
  • 根据条件 控制layui的table的toolbar的按钮 显示和不显示