[vue3] ref gets the elements rendered by the v-for loop

foreword

In vue2, we can bind the ref attribute to the element, and then use this.$refs.xxx to get the element.
In the vue3 version, you can continue to use the syntax of the option Api of vue2, or you can use the writing method of vue2.
Or use ref to bind the element, and then return the ref variable in the setup method, as follows:

<div :ref="myDom"> </div>

<script lang="ts">
...
  setup(){
    
    
    let myDom = ref(null)   
    console.log(myDom.value)   //这样就获取到这个元素了
    
    return {
    
    
      myDom
   }
  }
...
</script>

Problem
In the vue2 version, the element rendered by v-for can obtain its element array by binding ref.
However, using v-for to get elements in vue3 does not get the element array, only the last element traversed.

Solution

<div  v-for="item in 5" :key="index"  ref="getMyDom"> </div>

<script lang="ts">
...
  setup(){
    
    
    
    let myDom = ref([])
    //遍历获取元素,然后放在一个数组里
    function getMyDom(el){
    
    
      if(el) {
    
    
        myDom.value.push(el)
      }
    }
    console.log(myDom.value)   //这样就获取到v-for渲染的元素数组了
    return {
    
    
      getMyDom
   }
  }
...
</script>

Guess you like

Origin blog.csdn.net/qq_38974163/article/details/122623373#comments_27620676