Vue encourages reactive and declarative programming for maintainability. But sometimes direct DOM access is required. In those cases, the $el property gives you access to a component’s root HTML element after it has been mounted.
What is $el in Vue?
The $el property in Vue refers to the root DOM node of a component instance. It becomes available only after the component has been mounted.
mounted() { console.log(this.$el) // Logs the root HTML element
}
When Should You Use $el?
Use $el when:
1. Integrating Third-Party Libraries
When using external JS libraries (like jQuery, D3, etc.) that need a direct DOM reference, $el can be practical.
mounted() { const chart = new Chart(this.$el, chartOptions);
}
2. Accessing Element Properties
Sometimes, you might want to read DOM properties like scrollHeight or clientWidth:
mounted() { console.log(this.$el.scrollHeight);
}
Why $el is discouraged in Vue 3
Vue 3 encourages the separation of concerns and reactivity. $el accesses a raw DOM element and bypasses Vue’s reactivity system, making your code harder to maintain and debug.
// Avoid this:this.$el.style.display = 'none'
// Use Vue syntax:
<div v-show="isVisible">Hello</div>
Also Read: The Top Vue Developer Tools For Easy Coding
Alternatives to $el in Vue 3
Prefer Vue-native tools like refs and directives.
<template> <input ref="inputRef" />
</template>
<script setup>
import { ref, onMounted } from 'vue'
const inputRef = ref(null)
onMounted(() => {
inputRef.value.focus()
})
</script>
Best Practices for Using $el
Keep DOM access minimal and clean.
- Use $el only in the mounted() hook
- Avoid data mutations based on DOM state
- Prefer ref for maintainability and reactivity
Key Takeaway
Use $el only when you need to interact directly with the DOM and Vue’s reactive system doesn’t suffice. For most tasks, refs and directives are better.
Related Resources