最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - VueJS get Width of Div - Stack Overflow

programmeradmin3浏览0评论

I have a Vue Component, that uses the bootstrap grid. In the child ponent I would like to get the current width of a certain div in the controller.

heres the child ponent:

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

I have a Vue Component, that uses the bootstrap grid. In the child ponent I would like to get the current width of a certain div in the controller.

heres the child ponent:

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

Share Improve this question edited Sep 21, 2017 at 14:05 Jan Schmutz asked Sep 21, 2017 at 13:58 Jan SchmutzJan Schmutz 8903 gold badges12 silver badges32 bronze badges 3
  • 1 It seems to work fine in my jsfiddle, check it out: jsfiddle/ikbelkirasan/d18bosh6/1 – Ikbel Commented Sep 21, 2017 at 14:12
  • this is really weird, but in my example the ponent is a child ponent. Maybe it has something to do that children get mounted before parent ponents, so the width of 100% that points to the parent doesn't exist yet. – Jan Schmutz Commented Sep 21, 2017 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 Commented Sep 21, 2017 at 14:33
Add a ment  | 

1 Answer 1

Reset to default 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.

发布评论

评论列表(0)

  1. 暂无评论