Vue Template Refs

Vue Tutorial

 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


 

  • 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

TaskUse
Form datav-model
Focus / scrollref
DOM measurementref
State managementref
  • 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

ScenarioHow
DOM elementref="el"$refs.el
Child componentref="child"
Loop refs$refs.items[]
Vue 3 setupconst el = ref(null)
Access timemounted() / 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...