17

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

Jan Schmutz
  • 799
  • 3
  • 10
  • 28
  • 1
    It seems to work fine in my jsfiddle, check it out: https://jsfiddle.net/ikbelkirasan/d18bosh6/1/ – Ikbel Sep 21 '17 at 14:12
  • this is really weird, but in my example the component is a child component. Maybe it has something to do that children get mounted before parent components, so the width of 100% that points to the parent doesn't exist yet. – Jan Schmutz Sep 21 '17 at 14:18
  • You really want to create reproducible demo. I might know why I happens but then I need to create demo myself to verify. So you would really make it simpler by creating a demo. – dfsq Sep 21 '17 at 14:33

1 Answers1

7

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.

user1497119
  • 443
  • 6
  • 19
  • the parent element is a bootstrap div with col-md-9. As I said, when I inspect the element and its parent it has a width and height – Jan Schmutz Sep 21 '17 at 14:27
  • 6
    Beautiful (kidding) mix of super old school and ES6. – dfsq Sep 21 '17 at 14:32
  • As soon as you write "function" in your code, you will create a new scope. Thus you cannot access methods from without that scope using this. If you use an arrow function () => {}, this has same scope as the outer this. Sometimes you do need 2 scopes in one function, e. g. when a library binds an event to "this" and you want to access methods that are bound to an outer "this". – user1497119 Apr 14 '19 at 07:22