Vue Get Width and Height of Element

In this tutorial, we will learn how to get the width and height of elements using Vue.js. We will provide two examples. In the first example, we will use the Vue 3 Composition API, ref, and getBoundingClientRect(). In the second one, we will make use of Options API along with offsetWidth and offsetHeight to retrieve the width and height of elements.

written

reviewed

updated

Thanks for your feedback!
Your contributions will help us to improve service.
Example 1 : Use Vue 3 to Get Element width and Height
In this example, we use the Composition API to obtain the width and height of an element by using `ref` and `.getBoundingClientRect()`.
Vue 3 Get Element Height and Width (Composition Api)
Copied to Clipboard
xxxxxxxxxx
<script type="module">
const { createApp, ref,onMounted} = Vue
createApp({
setup() {
const elementRef = ref(null);
const elementWidth = ref(0);
const elementHeight = ref(0);
const getElementDimensions = () => {
if (elementRef.value) {
const {width,height} = elementRef.value.getBoundingClientRect();
elementWidth.value = width;
elementHeight.value = height;
}
};
onMounted(() => {
getElementDimensions();
});
return {
elementRef,
elementWidth,
elementHeight,
};
}
}).mount('#app')
</script>
Example 2: By using Vue Options Api to Get Element Width and Height
This is the second example of this tutorial. We use the Options API to get the element's width and height by using offsetHeight and offsetWidth
Vue Get Div Height and Width (Options Api)
Copied to Clipboard
xxxxxxxxxx
<script type="module">
const app = new Vue({
el: "#app",
data() {
return {
height: '',
width: ''
}
},
mounted() {
const element = this.$refs.myElement
this.width = element.offsetWidth
this.height = element.offsetHeight
}
});
</script>
Output of Vue Calculate Height and Width of Div
Ad