1

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.

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>
E_net4
  • 27,810
  • 13
  • 101
  • 139

1 Answers1

1

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>
MrSrv7
  • 585
  • 8
  • 22
  • I think this answer is only valid for the very specific case in which the container div corresponds to the whole window and reacts to a window resizing. If there is a container nested in another element whose size changes dynamically (e.g. due to changing content), another strategy is needed. – rubebop Sep 13 '22 at 13:26