Vue Template Refs
🔗 Vue Template Refs
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.
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
📌 this.$refs.input → actual DOM element
🔹 Access Timing (Important ⚠️)
Refs are available only after mount.
❌ Not available in created().
🔹 Ref with v-for
Refs inside loops become arrays.
🔹 Ref on Child Components
Refs can reference component instances, not just DOM.
Parent
Child
✔ Useful for modals, forms, custom inputs
🔹 Composition API: Template Refs (Vue 3)
✔ 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.
