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.
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.
Then we can get the element with the this.$refs
property in any lifecycle or regular methods.
For instance, we can write:
<template>
<div id="app">
<span ref="someName" class="foo bar">Child Span</span>
</div>
</template>
<script>
export default {
name: "App",
mounted() {
const childSpanClassAttr = this.$refs.someName.getAttribute("class");
console.log(childSpanClassAttr);
},
};
</script>
We set the ref
attribute of the span to someName
.
Then we can the span by writing this.$refs.someName
in any lifecycle or regular methods.
And we can call any DOM element method like getAttribute
on it.
We get the value of the class
attribute with 'class'
as the argument of getAttribute
.
Therefore, the console log logs 'foo bar’
.
Conclusion
To get an element within a component with Vue.js, we can assign a ref to the element we want to get.
Then we can get the element with the this.$refs
property in any lifecycle or regular methods.