Skip to main content

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.$refs in the Options API and ref() in the Composition API are available only after the DOM renders, in the mounted hook.


Why not earlier?

Before the mounted stage the component is not in the DOM, so:

  • the elements have not been created yet
  • this.$refs is empty
  • ref() 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) // null

Why does ref only appear in mounted?

Because Vue first:

  1. Runs setup() / the creation lifecycle hooks
  2. Creates the virtual DOM
  3. Mounts it into the real DOM
  4. Only now are refs bound to the DOM elements
  5. 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 ready
Premium

A concise answer to help you respond confidently on this topic during an interview.