最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Adding window.resize event in vuejs component is not working independently - Stack Overflow

programmeradmin1浏览0评论

I have a image slide ponent 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 ponent 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 ponent(i.e., Slider 2). For the first ponent(Slider 1) resize method is not working.

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

I have a image slide ponent 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 ponent 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 ponent(i.e., Slider 2). For the first ponent(Slider 1) resize method is not working.

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

Share Improve this question asked Oct 8, 2020 at 13:03 SamSam 2,4259 gold badges35 silver badges53 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 6

You are overriding the onresize handler every time, this causes only the last mounted ponent 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 ponent
 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);
}
发布评论

评论列表(0)

  1. 暂无评论