Menu Close

How to get the DOM element to corresponding Vue.js component with JavaScript?

Sometimes, we want to get the DOM element to corresponding Vue.js component with JavaScript.

In this article, we’ll look at how to get the DOM element to corresponding Vue.js component with JavaScript.

How to get the DOM element to corresponding Vue.js component with JavaScript?

To get the DOM element to corresponding Vue.js component with JavaScript, we can use refs.

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 assign the childElement ref to the div.

Then in the mounted hook, we get the root element of the component with this.$el.

And we get the div with this.$refs.childElement.

Conclusion

To get the DOM element to corresponding Vue.js component with JavaScript, we can use refs.

Posted in vue