Adding window.resize event in vuejs component is not working independently

Viewed 2154

I have a image slide component which has resize event

imageSliderComponent.vue

methods: {
 resize: function () {
   console.log(this.$el)
   // Handle window resize
   // Code
 }
}
mounted () {
 window.onresize = this.resize
}

And in the parent component i am using this image slider in multiple places, some thing like this

App.vue

<image-slider :data="data1" />   // Slider 1
<image-slider :data="data2" />   // Slider 2

So when i try to resize the window, window.resize event is working only for the last occurred component(i.e., Slider 2). For the first component(Slider 1) resize method is not working.

Is there any way to handle resize independently for reusable component? please suggest if there is any other different implementation.

1 Answers

You are overriding the onresize handler every time, this causes only the last mounted component to work.

You need to instead use addEventListener:

mounted () {
 // You probably also want to call .bind as otherwise the `this` will not point to the component
 this._boundedResize = this.resize.bind(this); // Store in a var in order to remove it later
 window.addEventListener("resize", this._boundedResize);
}

destroyed() {
 window.removeEventListener("resize", this._boundedResize);
}
Related