Episode 16 of 44
Refs
Access DOM elements directly with refs — an escape hatch for when you need to interact with the DOM outside of Vue's reactive system.
Refs
Sometimes you need to directly access a DOM element — for example, to focus an input, measure dimensions, or integrate with a third-party library. Vue provides refs for this purpose.
Setting a Ref
<input type="text" ref="nameInput">
<p ref="output">Hello</p>
<button @click="readRef">Read Ref</button>
The ref attribute gives you a named reference to the DOM element. You can then access it in your JavaScript code.
Accessing Refs
methods: {
readRef() {
console.log(this.$refs.nameInput.value); // Input value
console.log(this.$refs.output.innerText); // Element text
this.$refs.nameInput.focus(); // Focus the input
this.$refs.nameInput.classList.add('active');
}
}
All refs are available on this.$refs. Each ref gives you the raw DOM element, so you can use standard DOM properties and methods like .value, .innerText, .focus(), and .classList.
When to Use Refs
| Scenario | Use Refs? |
|---|---|
| Displaying data in the template | No — use {{ }} or v-bind |
| Focusing an input programmatically | Yes |
| Reading input values | Prefer v-model — use refs only when needed |
| Integrating with jQuery or D3 | Yes |
| Measuring element dimensions | Yes |
Key Takeaways
- Add
ref="name"to an element to create a reference - Access refs with
this.$refs.name— returns the raw DOM element - Refs are an escape hatch — prefer Vue's reactive system for data display and manipulation
- Useful for focus management, measurements, and third-party library integration