Vue – When and Why Using $el

Accessing the $el property in Vue provides direct control over the DOM element. This is useful in edge cases requiring manual DOM manipulation.

Summarize with AI

Not enough time? get the key points instantly.

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:

Hello

Alternatives to $el in Vue 3

Prefer Vue-native tools like refs and directives.

  

 

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


Resources

Insights from our engineering leaders.

Our team shares practical insights on the technologies and engineering decisions shaping enterprise software today, grounded in real client work.