SoFunction
Updated on 2025-04-05

vue3 loop set ref and get solution

Preface

vue can obtain the current dom through ref, but vue3 has a problem, that is, the variable name of the ref must be defined in order to use

If there are many refs, it would be too cumbersome to define them one by one. Also, if the dom is looped using v-for, then the ref will be uncertain and cannot be defined in advance.

Solution:

  • This is the dom that is looped using v-for, and ref is named by index subscript.
<div
 class="chart"
  v-for="(item, index) in riskSpreadItem"
  :key=""
>
  <Pie
    :
    :ref="el => getRiskSpreadRef(el, index)"
    :title=""
    :data=""
    emptyText="No risk yet"
  />
</div>
  • At this time, all refs are placed in riskSpreadRefList
const riskSpreadRefList = ref<HTMLElement[]>([]);
const getRiskSpreadRef = (el, index) => {
  if (el) {
    [index] = el; 
  }
};
  • Use: Just loop to get it, item is the dom element obtained through ref. You can operate the variables or methods defined above
?.forEach((item: any) =&gt; {
    (item)
});

There is also a way to get ref, which is slightly similar to the above. Please record it, but using push may cause the ref to get null before it has been rendered, so it is best to write it as above.

<div class="chart">
  <Pie
    :
    :ref="getRiskRef"
    :data=""
    @clickPie="queryRiskList"
  />
</div>
let riskRefList = ref<HTMLElement[]>([]);
const getRiskRef = (el) => {
  if (el) {
    (el);
  }
};
riskRefList .value?.forEach((item: any) => {
    (item)
});

Attachment: vue3 obtains the ref generated by dynamic loop

html part:

&lt;template&gt;
    &lt;div  v-for="(item,index) in list" :ref="setItemRef"&gt;
      {{item}}
    &lt;/div&gt;
    &lt;el-button @click="getRefData"&gt;Get&lt;/el-button&gt;
&lt;/template&gt;

js part

&lt;script lang="ts" setup&gt;
    import {ref,reactive,onMounted} from 'vue'
    const refList = ref([]); //Define the ref array    const list = reactive([
        "First row of data",
        "Second line of data",
        "Third line of data",
        "Fourth row of data",
    ])
    //Assign ref    const setItemRef = el =&gt; { 
        if (el) {
            (el);
        }
    }

	//Get ref and perform the next operation    const getRefData = ()=&gt;{
        for(let i =0; i &lt; ; i++){
            ([i]); // [i].xxx execute todo        }
    }
 &lt;/script&gt;

Summarize

This is the article about setting ref and obtaining vue3 loops. For more related vue3 loops, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!