vue3 sets dynamic ref in v-for invalid and solution

Friends who are anxious and afraid of verbosity can directly look at the final code. Friends who are not anxious can check whether the content is the same as what you need.

Recently, there was a need to upload 10 images. Each image has a different purpose. Since each image after uploading needs to undergo different special processing and be placed in a different div, it is necessary to store each image. Each div of the image is set with a ref, which is processed after the image is uploaded. This leads to another problem: setting dynamic refs for elements in v-for loops. Why use v-for? Because there are 10 pictures, it is too troublesome to write them one by one.

I originally thought that dynamic ref should be very simple, just write it like ordinary dynamic properties:

<div
    v-for="(item, index) in imgListData"
    :key="item.id"
  >
    <div
      :ref="`imgContainer${index+1}`"
    ></div>
</div>

Then just get the value in ts like this:

const imgContainer1: any = ref();
·
·
·
const imgContainer10: any = ref();

As a result, the imgContainer1.value printed in created is null, which means that setting the dynamic ref in v-for is invalid.

In fact, if it is not in v-for, there are variables that can be obtained when setting ref:

<div
  :ref="`imgContainer${refName}`"
></div>  

const refName = 'a';
const imgContainera: any = ref();

The above code prints imgContainera.value in created and it has value.

So how to set dynamic ref in the v-for loop? The method I used may not be the best, but it does get the elements. HTML code:

<div
  v-for="(item, index) in imgListData"
  :key="item.id"
>
  <div
    :ref="(el: any) => setRef(el, index+1)"
  ></div>
</div>

ts code:

<script lang="ts" setup>
// 设置动态 ref
  const setRef = (item: any, index: any) => {
    switch (index) {
      case 2:
        imgContainer2.value = item;
        break;
      case 3:
        imgContainer3.value = item;
        break;
      ···
      case 10:
        imgContainer10.value = item;
        break;
      default:
        imgContainer1.value = item;
    }
  };


const imgListData= reactive([   //  这个变量也可以用方法生成也可以直接定义
{
  id: 1,
   cname: '',
 },
 ...
 {
  id: 10,
   cname: '',
 },
]);

</script >

I hope this article is helpful to you, and I also hope that someone who knows better will criticize and correct me, and I will not hesitate to give you advice!

Guess you like

Origin blog.csdn.net/JaneLittle/article/details/129874580