[英]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.