Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access dynamic ref-tagged html elements in Vue.js 3?

Tags:

vuejs3

Using the Vue.js 2 api-composition, you have a .ref attribute on the setupContext argument of setup(). As stated in many articles and in this thread : https://github.com/vuejs/composition-api/issues/226 it will NOT be available in vue.js 3, and you should declare attributes of the same name as the ref-ed element :

<div ref='name'/>

setup() {
  return {
    name : ref(null)
  }
}

However, what about when you do not know the ref name at the setup() ?

Like this "minimum" example :

<div v-for="e in elements" @click="elements.push({name:Math.random(), content:Math.random()})">
  <div :ref="e.name">e.content</div>
</div>

setup(){
   return {
     a_function_called_later(){
       // I can use this.$refs but is there a more "vuejs3" way to do it ?
     }
     // ...???
   }
}
like image 769
hl037_ Avatar asked Apr 11 '20 11:04

hl037_


1 Answers

I had the same problem and was asking in the Vue.js Discord about it. Luckily Carlos Rodrigues could help me out.

<template>
  <div v-for="(item, i) in list" :ref="el => { divs[i] = el }">
    {{ item }}
  </div>
</template>

<script>
  import { ref, reactive, onBeforeUpdate } from 'vue'

  export default {
    setup() {
      const list = reactive([1, 2, 3])
      const divs = ref([])

      // make sure to reset the refs before each update
      onBeforeUpdate(() => {
        divs.value = []
      })

      return {
        list,
        divs
      }
    }
  }
</script>

You can read more about it in the official documentation: https://composition-api.vuejs.org/api.html#template-refs or on my blog: https://markus.oberlehner.net/blog/refs-and-the-vue-3-composition-api/

like image 132
moriartie Avatar answered Oct 18 '22 08:10

moriartie