vue3循環(huán)設(shè)置ref并獲取的解決方案
前言
vue可通過ref來獲取當(dāng)前dom,但是vue3有個問題,就是必須定義ref的變量名,才能使用
倘若有許多個ref,一個個去定義未免過于繁瑣,還有就是若是dom是使用v-for循環(huán)出來的,那么ref也就不確定了,無法提前定義
解決方法:
- 這是使用v-for循環(huán)出來的dom,ref通過index下標來命名,
<div class="chart" v-for="(item, index) in riskSpreadItem" :key="item.title" > <Pie :id="`riskSpread${index}`" :ref="el => getRiskSpreadRef(el, index)" :title="item.title" :data="item.data" emptyText="暫無風(fēng)險" /> </div>
- 此時riskSpreadRefList里面放的就是所有ref
const riskSpreadRefList = ref<HTMLElement[]>([]); const getRiskSpreadRef = (el, index) => { if (el) { riskSpreadRefList.value[index] = el; } };
- 使用:循環(huán)去取就行了,item就是通過ref拿到的dom元素??梢圆僮魃厦娑x的變量或方法
riskSpreadRefList.value?.forEach((item: any) => { console.log(item) });
還有一種獲取ref的方法,與上面略相似,記錄一下,但是用push可能會造成ref還沒渲染完得到null的情況,所以最好還是上面那樣寫
<div class="chart"> <Pie :id="`risk${index}`" :ref="getRiskRef" :data="item.data" @clickPie="queryRiskList" /> </div>
let riskRefList = ref<HTMLElement[]>([]); const getRiskRef = (el) => { if (el) { riskRefList.value.push(el); } };
riskRefList .value?.forEach((item: any) => { console.log(item) });
附:vue3獲取動態(tài)循環(huán)生成的ref
html部分:
<template> <div v-for="(item,index) in list" :ref="setItemRef"> {{item}} </div> <el-button @click="getRefData">獲取</el-button> </template>
js部分
<script lang="ts" setup> import {ref,reactive,onMounted} from 'vue' const refList = ref([]); //定義ref數(shù)組 const list = reactive([ "第一行數(shù)據(jù)", "第二行數(shù)據(jù)", "第三行數(shù)據(jù)", "第四行數(shù)據(jù)", ]) //賦值ref const setItemRef = el => { if (el) { refList.value.push(el); } } //獲取ref并執(zhí)行接下來操作 const getRefData = ()=>{ for(let i =0; i < refList.value.length; i++){ console.log(refList.value[i]); // refList.value[i].xxx 執(zhí)行todo } } </script>
總結(jié)
到此這篇關(guān)于vue3循環(huán)設(shè)置ref并獲取的文章就介紹到這了,更多相關(guān)vue3循環(huán)設(shè)置ref并獲取內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
基于vue+elementPlus的動態(tài)導(dǎo)航標簽欄tabs具體過程
這篇文章主要給大家介紹了關(guān)于基于vue+elementPlus的動態(tài)導(dǎo)航標簽欄tabs的相關(guān)資料,本文主要詳述了在系統(tǒng)上添加導(dǎo)航標簽欄功能時,首次嘗試的過程,并且希望能為同行提供一個小demo,需要的朋友可以參考下2024-10-10示例vue 的keep-alive緩存功能的實現(xiàn)
這篇文章主要介紹了示例vue 的keep-alive緩存功能的實現(xiàn),小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-12-12詳解vue-cli項目中怎么使用mock數(shù)據(jù)
這篇文章主要介紹了vue-cli項目中怎么使用mock數(shù)據(jù),小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-05-05Vue2和Vue3在v-for遍歷時ref獲取dom節(jié)點的區(qū)別及說明
這篇文章主要介紹了Vue2和Vue3在v-for遍歷時ref獲取dom節(jié)點的區(qū)別及說明,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-03-03