Home > Software design >  How to get dynamic width of a specific div in vue?
How to get dynamic width of a specific div in vue?

Time:03-06

I am trying to get the width of a container dynamically in vue with the help of refs. But, either it is returning the previous value, or it is showing undefined. I am guessing I am doing something wrong. I just want the width of a particular div dynamically. Please don't downvote. I am relatively new to vue.

I referred 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 no luck

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>

CodePudding user response:

You need to set ref in template, so try like following snippet:

const app = new Vue({
   el: '#app',
   data() {
     return {
       sWidth: ''
     }
   },
   mounted () {
     this.screenWidth()
   },
   methods: {
      screenWidth() {
      this.sWidth = 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 {{ sWidth }}
</div>

CodePudding user response:

On top of Vue JS - How to get window size whenever it changes 's accepted answer, you can add a mounted() call always to have the width.

const app = new Vue({
   el: '#app',
   data() {
    return {
      sWidth: null
    };
  },
  created() {
    window.addEventListener("resize", this.screenWidth);
  },
  mounted () {
    this.screenWidth()
  },
  destroyed() {
    window.removeEventListener("resize", this.screenWidth);
  },
  methods: {
    screenWidth() {
      this.sWidth = 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 {{ sWidth }}
</div>

  • Related