繁体   English   中英

在 vuejs 组件中添加 window.resize 事件不能独立工作

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

我有一个具有调整大小事件的图像幻灯片组件

imageSliderComponent.vue

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

在父组件中,我在多个地方使用这张图片 slider,像这样

App.vue

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

因此,当我尝试调整 window 的大小时,window.resize 事件仅适用于最后出现的组件(即 Slider 2)。 对于第一个组件(Slider 1),调整大小的方法不起作用。

有没有办法独立处理可重用组件的调整大小? 请建议是否有任何其他不同的实现。

您每次都在覆盖onresize处理程序,这只会导致最后安装的组件工作。

您需要改用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);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM