Vue Template Refs

🔗 Vue Template Refs

In Vue.js, template refs give you direct access to DOM elements or child component instances from your JavaScript code.

They are useful when you need imperative control—things that can’t be done declaratively.


🔹 What are Template Refs?

A template ref is created by adding the ref attribute to an element or component in the template.

<input ref="usernameInput" />

You can then access it in JavaScript after the component is mounted.


🔹 When Should You Use Refs?

Use refs sparingly for:

  • Focusing inputs

  • Scrolling to elements

  • Measuring element size/position

  • Calling methods on child components

  • Integrating third-party libraries

❌ Avoid refs for normal data flow (use props / emits / state).


🔹 Options API: Basic Example

<template>
<input ref="input" />
<button @click="focusInput">Focus</button>
</template>
<script>
export default {
methods: {
focusInput() {
this.$refs.input.focus()
}
}
}
</script>

📌 this.$refs.input → actual DOM element


🔹 Access Timing (Important ⚠️)

Refs are available only after mount.

mounted() {
console.log(this.$refs.input) // ✅ available
}

❌ Not available in created().


🔹 Ref with v-for

Refs inside loops become arrays.

<template>
<li v-for="item in items" :key="item.id" ref="rows">
{{ item.name }}
</li>
</template>
mounted() {
this.$refs.rows.forEach(el => {
console.log(el.textContent)
})
}

🔹 Ref on Child Components

Refs can reference component instances, not just DOM.

Parent

<ChildComponent ref="child" />
this.$refs.child.someMethod()

Child

methods: {
someMethod() {
console.log("Called from parent")
}
}

✔ Useful for modals, forms, custom inputs


🔹 Composition API: Template Refs (Vue 3)

<template>
<input ref="inputEl" />
<button @click="focus">Focus</button>
</template>
<script setup>
import { ref, onMounted } from ‘vue’

const inputEl = ref(null)

const focus = () => {
inputEl.value.focus()
}

onMounted(() => {
console.log(inputEl.value)
})
</script>

ref(null) → filled after mount
✔ Access via .value


🔹 Refs vs v-model

Task Use
Form data v-model
Focus / scroll ref
DOM measurement ref
State management ref

✔ Use refs for imperative DOM actions only.


🔹 Common Mistakes ❌

❌ Using refs for regular state
❌ Accessing refs before mount
❌ Overusing refs instead of props/emits
❌ Mutating DOM heavily via refs


🔹 Best Practices ✅

✔ Prefer declarative patterns first
✔ Use refs only when necessary
✔ Name refs clearly (inputEl, modalRef)
✔ Avoid deep ref chains
✔ Clean up when using third-party libs


🔹 Summary Table

Scenario How
DOM element ref="el"$refs.el
Child component ref="child"
Loop refs $refs.items[]
Vue 3 setup const el = ref(null)
Access time mounted() / onMounted()

🏁 Conclusion

Vue template refs are a powerful escape hatch for direct DOM and component access.
Use them carefully and intentionally to keep your Vue apps clean and maintainable.

You may also like...