Sometimes, we want to get the DOM element for the corresponding Vue.js component.
In this article, we’ll look at how to get the DOM element for the corresponding Vue.js component.
Get the DOM Element for the Corresponding Vue.js Component
We can get the root element of the component with the this.$el
property.
And to get a child element, we can assign a ref to it and then reference it with this.$refs
.
For instance, we can write:
<template>
<div id="app">
root element
<div ref="childElement">child element</div>
</div>
</template>
<script>
export default {
name: "App",
mounted() {
const rootElement = this.$el;
const childElement = this.$refs.childElement;
console.log(rootElement);
console.log(childElement);
},
};
</script>
this.$el
is the div with ID app
.
And we assign the ref
prop of the inner div with value childElement
.
So we can get the inner div element with this.$refs.childElement
.
And the corresponding values are logged in the console log.
Conclusion
We can get the root element of the component with the this.$el
property.
And to get a child element, we can assign a ref to it and then reference it with this.$refs
.