I am currently facing an issue while trying to obtain the width of a container dynamically in Vue using refs. The problem I am encountering is that it either shows the previous value or returns undefined. I suspect there might be a mistake in my approach. My main goal is to retrieve the width of a specific div in real-time.
In my quest for a solution, I came across helpful discussions on Vue - Setting the width of a component dynamically, vuetify.js how to get full width of v-container, and Vue - setting width of an element equal to the width of another element, but unfortunately, none of them worked for me.
const app = new Vue({
el: '#app',
mounted () {
this.screenWidth()
},
methods: {
screenWidth() {
console.log("screen", this.$refs.container?.offsetWidth);
return `${this.$refs?.container?.offsetWidth}`;
},
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app" ref="container">
Screen {{ screenWidth() }}
</div>