When do ref elements become available?
ref elements become available only after the component has been mounted, that is, in the mounted hook (or later).
In simple terms:
this.$refsin the Options API andref()in the Composition API are available only after the DOM renders, in themountedhook.
Why not earlier?
Before the mounted stage the component is not in the DOM, so:
- the elements have not been created yet
this.$refsis emptyref()references are not bound
ref availability in different APIs
Options API
In created()
js
created() {
console.log(this.$refs.input) // undefined
}In mounted()
js
mounted() {
console.log(this.$refs.input) // <input ...>
}Composition API
Using ref():
html
<input ref="inputEl" />In setup():
js
const inputEl = ref(null)
onMounted(() => {
console.log(inputEl.value) // DOM element
})Before mounted:
js
console.log(inputEl.value) // nullWhy does ref only appear in mounted?
Because Vue first:
- Runs
setup()/ the creation lifecycle hooks - Creates the virtual DOM
- Mounts it into the real DOM
- Only now are refs bound to the DOM elements
- Calls
mounted
And only now are all refs correct.
Example
vue
<template>
<input ref="field" />
</template>
<script>
export default {
mounted() {
// Now the DOM element is available
this.$refs.field.focus()
}
}
</script>A special case: ref on a component
When you do:
html
<MyComponent ref="comp" />this.$refs.comp is the instance of the child component.
It is also available only in mounted.
Exceptions?
- Teleport can delay the appearance of the DOM element, so the ref won't be available right away in mounted.
- v-if can create the component later, so the ref updates later, upon activation.
But there is one rule:
ref is always available after the DOM node physically exists.
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.