Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VueJS get Width of Div

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

like image 993
Jan Schmutz Avatar asked Sep 21 '17 13:09

Jan Schmutz


People also ask

How do I get height element in Vue?

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.

How do you find the width of an element?

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.

What is ref Vue 3?

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.

How do you get parent elements in Vue?

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.


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.

like image 196
user1497119 Avatar answered Oct 04 '22 14:10

user1497119