Sometimes, we want to get the DOM element that correspond to the Vue.js component.
In this article, we’ll look at how to get the DOM element that correspond to the Vue.js component.
How to get DOM element that correspond to the Vue.js component?
To get the DOM element that correspond to the Vue.js component, we can use this.$el
to get the root element of the current component.
And we can use this.$refs
to get the element that’s been assigned the ref.
For instance, we write
<template>
<div>
root element
<div ref="childElement">child element</div>
</div>
</template>
<script>
export default {
mounted() {
const rootElement = this.$el;
const childElement = this.$refs.childElement;
console.log(rootElement);
console.log(childElement);
},
};
</script>
to get the root div with this.$el
.
And we get the div that’s been assigned the childElement
with ref="childElement"
with this.$refs.childElement
.
Conclusion
To get the DOM element that correspond to the Vue.js component, we can use this.$el
to get the root element of the current component.
And we can use this.$refs
to get the element that’s been assigned the ref.