首页 > 解决方案 > 每次调整窗口大小时如何运行挂载函数然后销毁事件侦听器

问题描述

我有以下挂载的函数,然后我想在每次调整窗口大小时运行它。我还想在事件运行后使用 destroy() 删除事件。任何帮助都会受到极大的欢迎。

mounted() {
    const modalHeight = this.$refs.modal.getBoundingClientRect().height
    const wrapperHeight = 
this.$refs.modalWrapper.getBoundingClientRect().height

if (wrapperHeight > modalHeight) {
  this.$refs.modal.addEventListener('mousemove', (e) => {
    const diffHeight = wrapperHeight - modalHeight
    const multiplier = diffHeight / 100
    const steps = 100 / modalHeight
    const shiftPerc = Math.floor(e.clientY * steps)

    this.$refs.modalWrapper.style.transform = `translateY(${multiplier * shiftPerc * -1}px)`
  })
}

},

标签: vue.js

解决方案


您可以将函数移动到其中的单独部分,methods并以它作为参考添加/删除事件侦听器。

另外,请注意,由于resize事件可以高速触发,因此事件处理程序不应执行计算量大的操作。相反,建议限制消除事件。

使用lodash.debounce()函数的示例。

export default {
  mounted() {
    window.addEventListener('resize', _.debounce(this.updateModal, 250));
  },

  methods: {
    updateModal() {
      const modalHeight = this.$refs.modal.getBoundingClientRect().height;
      const wrapperHeight = this.$refs.modalWrapper.getBoundingClientRect().height;

      if (wrapperHeight > modalHeight) {
        this.$refs.modal.addEventListener('mousemove', (e) => {
          const diffHeight = wrapperHeight - modalHeight;
          const multiplier = diffHeight / 100;
          const steps = 100 / modalHeight;
          const shiftPerc = Math.floor(e.clientY * steps);

          this.$refs.modalWrapper.style.transform = `translateY(${multiplier * shiftPerc * -1}px)`;
        });
      }
    }
  },

  destroy() {
    window.removeEventListener('resize', this.updateModal);
  }
})

推荐阅读