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

相关推荐
小张成长计划..21 分钟前
前端6:CSS3 2D转换,CSS3动画,CSS3 3D转换
前端·3d·css3
IT_陈寒25 分钟前
Vue3性能优化实战:这7个技巧让我的应用加载速度提升50%!
前端·人工智能·后端
西西学代码39 分钟前
Flutter---音效模式选择器
前端·html
TLucas42 分钟前
Layui连线题编辑器组件(ConnectQuestion)
前端·编辑器·layui
艾小码1 小时前
告别页面呆板!这5个DOM操作技巧让你的网站活起来
前端·javascript
正在学习前端的---小方同学3 小时前
vue-easy-tree树状结构
前端·javascript·vue.js
毕业设计制作和分享4 小时前
springboot150基于springboot的贸易行业crm系统
java·vue.js·spring boot·后端·毕业设计·mybatis
键盘不能没有CV键6 小时前
【图片处理】✈️HTML转图片字体异常处理
前端·javascript·html
yantuguiguziPGJ7 小时前
WPF 联合 Web 开发调试流程梳理(基于 Microsoft.Web.WebView2)
前端·microsoft·wpf
大飞记Python7 小时前
部门管理|“编辑部门”功能实现(Django5零基础Web平台)
前端·数据库·python·django