vue3组件ref属性用法,动态绑定ref

常见用法

TypeScript 复制代码
<template>
    <CustomWin  ref="sectionRef" class="ref-section"></CustomWin >
    <button @click="xx">点击</button>
</template>

<script setup lang="ts">
import {ref} from 'vue'
import CustomWin from "./CustomWin.vue"
const sectionRef = ref<InstanceType<typeof CustomWin>>();

function xx(){
    if(sectionRef.value){
       // sectionRef.value.xxx 调用
    }
}

</script>

如果我们需要在代码里面动态绑定ref,如果处理?

其实ref属性可以是个函数,(el)=>{},这样想怎样存储ref就可以怎样存储

TypeScript 复制代码
<template>
  <div v-for="(item, i) in list" :ref="el => { divs[i] = el }">
    {{ item }}
  </div>
</template>

<script>
import {
  onBeforeUpdate,
  reactive,
  ref,
} from 'vue';

export default {
  setup() {
    const list = reactive([1, 2, 3]);
    const divs = ref([]);

    // Make sure to reset the refs before each update.
    onBeforeUpdate(() => {
      divs.value = [];
    });

    return {
      list,
      divs,
    };
  },
};
</script>

注:el是就是vue实例,赋值后访问的时候无需xx.value

相关推荐
小徐_233313 分钟前
uni-app 组件库 Wot UI 2.0 发布了,我们带来了这些改变!
前端·微信小程序·uni-app
❀͜͡傀儡师18 分钟前
Claude Code 官方弃用 npm 安装方式:原因分析与完整迁移指南
前端·npm·node.js·claude code
知识分享小能手24 分钟前
ECharts入门学习教程,从入门到精通,ECharts高级功能(6)
前端·学习·echarts
阿祖zu24 分钟前
OpenClaw 入门到放弃:私人 AI 的初代原型机
前端·后端·aigc
ZC跨境爬虫25 分钟前
3D地球卫星轨道可视化平台开发 Day15(添加卫星系列模糊搜索功能)
前端·数据库·3d·交互·数据可视化
m0_7381207244 分钟前
渗透基础知识ctfshow——Web应用安全与防护(第六 七章)
服务器·前端·安全
Sun子矜44 分钟前
Web项目18+项目21
前端
踩着两条虫1 小时前
VTJ:项目模型架构
前端·低代码·ai编程
踩着两条虫1 小时前
VTJ:DSL语言规范
前端·低代码·ai编程
广州华水科技1 小时前
单北斗GNSS在水库形变监测中的应用与优势分析
前端