Skip to content
Advertisement

Vue update data prop whenever element clientWidth changes

I’m currently setting a data prop called w to whatever the clientWidth is for an element that I have in my HTML. It looks like this within my mounted hook:

data() {
 return {
  w: 0,
 };
},
mounted() {
  this.w = this.$refs.timelineProgress.clientWidth;
},

This works fine for initially setting this.w width that element’s clientWidth but what I’m trying to do now is change the value of w whenever the clientWidth changes. This is so I can get the width of the element and store it whenever it shrinks or grows based on a devices screen size or if a user shrinks a page or something like that.

Any help solving this is greatly appreciated. Thank you.

Advertisement

Answer

you can probably try using created and unmounted method to attach a window resize event to your component.

created() {
    window.addEventListener('resize', this.resizeHandler);
}
unmounted() {
    window.removeEventListener('resize', this.resizeHandler);
}
methods: {
    resizeHandler() {
        this.w = this.$refs.timelineProgress.clientWidth;
    }
}

In the resizeHandler method you can also debounce the state updation to make it more performant.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement