I have a Vue Component, that uses the bootstrap grid. In the child component I would like to get the current width of a certain div in the controller.
heres the child component:
<template>
<div id="bg-prev" ref="prev">
<h1>{{x}}</h1>
</div>
<template>
export default {
props: ['section'],
data() {
return {
x: 0,
y: 0,
}
},
mounted() {
this.getWindowWidth();
},
methods: {
getWindowWidth() {
this.x = this.$refs.prev.clientWidth;
}
}
};
<style>
#bg-prev {
width: 100%;
}
</style>
In this example the width will always be 0, even though the element has a clear width when I inspect it. What am I missing here, the mounted hook is the latest one in the vue lifecycle right? Any Help is appreciated ;)
To get an element's height with Vue. js, we can assign a ref to the element we want to get the height for. Then we can get the height with the clientHeight property of the element that's been assigned the ref. We assigned the ref with the ref prop set to a name.
The offsetWidth property returns the viewable width of an element (in pixels) including padding, border and scrollbar, but not the margin. The offsetWidth property is read-only.
ref() # Takes an inner value and returns a reactive and mutable ref object, which has a single property . value that points to the inner value. Type.
We can access the root Vue instance with $root , and the parent component with $parent . To access a child component from a parent, we can assign a ref with a name to the child component and then use this. $refs to access it.
Apart from a few typos the code is perfectly working. (missing closing template tag)
There is no additional hook needed. Only exception would be if you toggle the rendering of the Component in it's mounted method. Then you would use something like
const that = this
that.showDiv = true
that.$nextTick(function () {
that.getWindowWidth()
})
Are you sure it's parent is having a width during mounted? 100% of 0px is still 0px.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With