Categories
Vue Answers

How to get an element within a component with Vue.js?

Spread the love

Sometimes, we want to get an element within a component with Vue.js.

In this article, we’ll look at how to get an element within a component with Vue.js.

How to get an element within a component with Vue.js?

To get an element within a component with Vue.js, we can assign a ref to the element we want to get.

For instance, we write

<template>
  <div id="app">
    Parent.
    <span ref="someName" class="abc">Child Span</span>
  </div>
</template>

<script>
//...
export default {
  //...
  mounted() {
    const childSpanClassAttr = this.$refs.someName.getAttribute("class");
    console.log(childSpanClassAttr);
  },
  //...
};
</script>

to assign the someName ref to the span in the template.

Then we get the span in the mounted hook with

this.$refs.someName

And we can use any element method like getAttribute on the element returned by the ref.

Conclusion

To get an element within a component with Vue.js, we can assign a ref to the element we want to get.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *