Summary of several ways to get ref elements in vue3

Recently developed a new project on the PC side, which has such a requirement, click on the uploaded picture in the form (multiple pictures can be uploaded in this column), when previewing, a carousel effect will appear, showing the current Click on the picture, click and swipe left and right to preview the previous or next picture. Because you want to display the effect of which one you click, you need to set the name of the current picture in the carousel, so that the current picture will be displayed. At this time, ref is used to obtain the carousel Elements.

1. ref gets a single dom element:

<template>
   <div ref='divDom'></div> 
</template>
<script setup>
const divDom = ref(null);
onMounted(()=>{
    
    
    console.log('获取dom元素',divDom)
})

2. ref gets the dom element in the v-for loop:

<template>
   <div ref='getDivDom' v-for="item in list" :data-id="item.id"></div> 
</template>
<script setup>
const divDomList = ref(new Map());

const getDivDom = el=>{
    
    
    if(el){
    
    
        divDomList.set(el.dataset['id'],el) 
    }
}

// const el =divDomList.get(id) // 根据list数据中的id值 获取对应的dom元素 

Or use the following method (I am using the following method)

<template>
   <div ref='getDivDom' :ref="(el) => getDivDom(el, item)" v-for="item in list"></div> 
</template>
<script setup>
const divDomList = ref(new Map());

const getDivDom = (el,item)=>{
    
    
    if(el){
    
    
        divDomList.set(item.id, el) 
    }
}

// const el =divDomList.get(id) // 根据list数据中的id值 获取对应的dom元素

Here is my code after using the above method:

<template>
   <!-- 轮播图效果 -->
   <el-carousel
     arrow="always"
     :autoplay="false"
     @change="handlecar"
     :v-if="imgList.length > 0"
     :ref="(el) => getCarou(el, tab.id)"
     :data-id="tab.ruleId"
   >
      <el-carousel-item
         v-for="(item, index) in imgList"
         :key="index"
         :name="item.id"
         style="text-align: center"
      >
         <img :src="item.url" alt="" />
     </el-carousel-item>
  </el-carousel> 
</template>
<script setup>
const divDomList = ref(new Map());

//获取轮播元素
const getCarou = (el, id) => {
    
    
    if (el) {
    
    
        divDomList.value.set(id, el);
    }
};

//手动切换轮播图
const setActiveItem = (i, id) => {
    
    
    nextTick(() => {
    
    
        if (divDomList.value.get(id)) {
    
    
            divDomList.value.get(id).setActiveItem(i);
        }
    });
};

                        

Guess you like

Origin blog.csdn.net/xiaolinlife/article/details/131557764