zuramai
zuramai

Reputation: 51

Vue 3 template refs dynamic name

I noticed that to make a template ref in Vue 3 composition api <script setup>, I should make a variable name with the exact same as the ref value.

For example in Vue 3 documentation:

<template>
  <div ref="root">This is a root element</div>   <--- notice the ref name "root"
</template>

<script>
  import { ref, onMounted } from 'vue'

  export default {
    setup() {
      const root = ref(null)   <---- and the variable name should be "root" too

      onMounted(() => {
        console.log(root.value) 
      })

      return {
        root
      }
    }
  }
</script>

I was wondering if I can use the ref the way as Vue 2 do, because I have elements whose ref is random string, and it works on Vue 2 by just passing the name on $refs object.

<div ref="myCustomRefName"></div>

<script>
let myRef = this.$refs["myCustomRefName"]
</script>

But I can't do that since in Vue3, I should similarize the variable name and the ref prop value. Any help will be appreciated.

Upvotes: 5

Views: 13682

Answers (2)

keplerk
keplerk

Reputation: 79

What worked for me was the following

<template>
  <div ref="root">This is a root element</div>   <--- notice the ref name "root"
  <div ref="foo">this is foo element</div>
  <div ref="bar">this is bar element</div>
</template>

<script>
  import { ref, onMounted } from 'vue'

  export default {
    setup() {
      const refs = {
         root: ref(null), //<---- and the variable name should be "root" too
         foo: ref(null),
         bar: ref(null)
      }
      onMounted(() => {
        console.log(root.value)
        console.log(refs["root"])
      })

      return {
        ...refs
      }
    }
  }
</script>

Just create an object refs (i called it refs just due nostalgia) and call with any dynamic name you have.

Upvotes: 7

Wenfang Du
Wenfang Du

Reputation: 11307

Quote from the ref documentation:

<template>
  <!-- When bound dynamically, we can define ref as a callback function, passing the element or component instance explicitly -->
  <child-component :ref="el => (child = el)"></child-component>
</template>

child in the above code is a variable, you can name whatever you like ;).

Upvotes: 4

Related Questions