VueJS get Width of Div

Viewed 30235

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 ;)

1 Answers

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.

Related