情况是这样的,我的子组件是一个table表格,在内部需要监听resize来计算表格高度,然后一个页面有时会有多个表格。
在子组件table
中我用了lodash
的debounce
方法去处理了计算表格高度的方法,定义为handleResize
。然后测试时发现,防抖处理后,只会执行一个子组件实例的方法.
窗口大小发生变化时,怎么样才能让每个子组件在最后一次窗口变化时都能成功的触发我的事件呢
子组件table.vue
:
<template>
<p>table</p>
</template>
<script>
import _ from "lodash"
export default {
name: "table",
beforeDestroy() {
window.removeEventListener("resize", this.handleResize, true);
},
created() {
console.log("created uid:", this._uid);
window.addEventListener("resize", this.handleResize, true);
},
methods: {
handleResize: _.debounce(function () {
//this.calcTableHeight() //根据情况计算表格高度
console.log("handleResize uid: ", this._uid)
}, 200),
}
}
</script>
父页面page.vue
<template>
<table></table>
<table></table>
</template>
<script>
import table from "./table.vue";
export default {
name: "page",
components: {
table
}
}
</script>
然后,鼠标调整窗口大小以触发window的resize事件,测试结果如下:
table.vue?6c75:13 created uid: 10
table.vue?6c75:13 created uid: 11
table.vue?6c75:18 handleResize uid: 11