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

相关推荐
亿元程序员8 分钟前
别人家的蚂蚁搬家游戏一周赚1.6万?我反省了一下我的...
前端
用户693717500138410 分钟前
AI 用久了,我发现自己越来越不想找人聊天了
前端·后端·github
恋猫de小郭12 分钟前
Flutter Perfetto:Dart Heap Sampling 终于要接入 Android 原生内存分析了
android·前端·flutter
Highcharts.js2 小时前
Highcharts 在商业智能中的实战应用:释放数据洞察
前端·人工智能·算法·信息可视化·数据分析·数据可视化·highcharts
沐言人生10 小时前
自媒体人的效率神器!监控、采集、下载、发布,这个免费开源工具全拿下!
前端·vue.js·后端
怕浪猫12 小时前
NVIDIA 全产品谱系与演进
javascript·面试·github
excel12 小时前
为什么 super 中能接收到 resolve 和 reject?
前端
Flynt14 小时前
AI 生成的界面,能放心点吗?我把 Google A2UI 的三层防线拆开测了一遍
前端·google·agent
前端混子15 小时前
我用 AI 做了个「禾月小历」,一套代码跑微信小程序和 H5
前端