一个页面包含多个同一组件,子组件监听的resize事件经过防抖处理,只能触发一个组件

新手上路,请多包涵

情况是这样的,我的子组件是一个table表格,在内部需要监听resize来计算表格高度,然后一个页面有时会有多个表格。
在子组件table中我用了lodashdebounce方法去处理了计算表格高度的方法,定义为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
阅读 2.3k
1 个回答
子组件方法调用改成如下即可;另外,resize等事件应该是用节流吧?
<script>
    import _ from "lodash"
    export default {
        name: "table",
        beforeDestroy() {
            window.removeEventListener("resize", this.debounce, true);
        },
        created() {
            console.log("created uid:", this._uid);
            this.debounce = _.debounce(this.handleResize, 200);
            window.addEventListener("resize", this.debounce, true);
        },
        methods: {
            handleResize() {
                //this.calcTableHeight() //根据情况计算表格高度
                console.log("handleResize uid: ", this._uid)
            },
        }
    }
</script>
推荐问题