Template Refs

This section uses single-file component syntax for code examples

This guide assumes that you have already read the Composition API Introduction and Reactivity Fundamentals. Read that first if you are new to Composition API.

When using the Composition API, the concept of reactive refs and template refs are unified. In order to obtain a reference to an in-template element or component instance, we can declare a ref as usual and return it from setup():

  1. <template>
  2. <div ref="root">This is a root element</div>
  3. </template>
  4. <script>
  5. import { ref, onMounted } from 'vue'
  6. export default {
  7. setup() {
  8. const root = ref(null)
  9. onMounted(() => {
  10. // the DOM element will be assigned to the ref after initial render
  11. console.log(root.value) // <div>This is a root element</div>
  12. })
  13. return {
  14. root
  15. }
  16. }
  17. }
  18. </script>

Here we are exposing root on the render context and binding it to the div as its ref via ref="root". In the Virtual DOM patching algorithm, if a VNode’s ref key corresponds to a ref on the render context, the VNode’s corresponding element or component instance will be assigned to the value of that ref. This is performed during the Virtual DOM mount / patch process, so template refs will only get assigned values after the initial render.

Refs used as templates refs behave just like any other refs: they are reactive and can be passed into (or returned from) composition functions.

Usage with JSX

  1. export default {
  2. setup() {
  3. const root = ref(null)
  4. return () =>
  5. h('div', {
  6. ref: root
  7. })
  8. // with JSX
  9. return () => <div ref={root} />
  10. }
  11. }

Usage inside v-for

Composition API template refs do not have special handling when used inside v-for. Instead, use function refs to perform custom handling:

  1. <template>
  2. <div v-for="(item, i) in list" :ref="el => { divs[i] = el }">
  3. {{ item }}
  4. </div>
  5. </template>
  6. <script>
  7. import { ref, reactive, onBeforeUpdate } from 'vue'
  8. export default {
  9. setup() {
  10. const list = reactive([1, 2, 3])
  11. const divs = ref([])
  12. // make sure to reset the refs before each update
  13. onBeforeUpdate(() => {
  14. divs.value = []
  15. })
  16. return {
  17. list,
  18. divs
  19. }
  20. }
  21. }
  22. </script>