$refs
Template refs give you direct access to a DOM element or child component instance.
In this page:
Syntax
<input ref="name">
mounted() {
this.$refs.name.focus();
}
$refs
Add ref="name" to an element or component and read it from this.$refs.name after mounting. It is the escape hatch for things like focusing an input or calling a child's method. Avoid using refs to change state that could flow through props.
Note:
Refs are only available after the component is mounted.
Example: $refs
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
</head>
<body>
<div id="app">
<input ref="box" value="focus me">
<child-counter ref="child"></child-counter>
</div>
<script>
const app = Vue.createApp({
mounted() {
this.$refs.box.focus();
this.$refs.child.bump();
console.log("input focused:", document.activeElement === this.$refs.box);
console.log("child count via ref:", this.$refs.child.n);
},
});
app.component("child-counter", {
data() { return { n: 0 }; },
methods: { bump() { this.n++; } },
template: "<p>n = {{ n }}</p>",
});
app.mount("#app");
</script>
</body>
</html>
<!-- Output:
Rendered: n = 1
console: input focused: true
console: child count via ref: 1
-->
Live Example
Related Topics
Common Mistakes
- Reading refs before mounted
- Using refs instead of props and events
- Forgetting refs inside v-for are arrays
Chapter Summary
- ref attribute registers a reference
- Read this.$refs after mount
- Good for focus and imperative calls
- Prefer props and events for data
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: