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.