#1 Data Analytics Program in India
₹2,499₹1,499Enroll Now
3 min read
Question 16 of 37easy

What are Template Refs in Vue?

Direct access to DOM elements.

What You'll Learn

  • Accessing DOM elements
  • Component refs
  • Refs in v-for

Basic Template Ref

code.txtVUE
<script setup>
import { ref, onMounted } from 'vue'

const inputRef = ref(null)

onMounted(() => {
  inputRef.value.focus()
})
</script>

<template>
  <input ref="inputRef" />
</template>

Component Ref

code.txtVUE
<script setup>
import { ref } from 'vue'
import ChildComponent from './ChildComponent.vue'

const childRef = ref(null)

function callChildMethod() {
  childRef.value.someMethod()
}
</script>

<template>
  <ChildComponent ref="childRef" />
</template>

<!-- ChildComponent must expose methods -->
<script setup>
defineExpose({
  someMethod() {
    console.log('Called from parent')
  }
})
</script>

Refs in v-for

code.txtVUE
<script setup>
import { ref } from 'vue'

const itemRefs = ref([])
</script>

<template>
  <li v-for="item in items" :ref="el => itemRefs.push(el)">
    {{ item }}
  </li>
</template>