每次调整窗口大小然后销毁事件侦听器时如何运行安装的函数 [英] How to run a mounted function everytime the window is resized and then destroy the event listener
问题描述
我有以下挂载的函数,然后我想在每次调整窗口大小时运行它.我还想使用 destroy() 在运行后删除事件.任何帮助将不胜感激.
I have the following mounted function that I would then like to run every time the window is resized. I would also like to use destroy() to delete the event after its run. Any help would be greatly received.
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)`
})
}
},
推荐答案
您可以将函数移动到 methods
中的一个单独部分,并以它作为参考添加/删除事件侦听器.
You could move the function to a separate section within methods
and add/remove the event listener with it as the reference.
>
另外,请注意,由于 resize
事件可以高速率触发,事件处理程序不应执行计算成本高的操作.相反,建议节流或
Also, be advised that since resize
events can fire at a high rate, the event handler shouldn't execute computationally expensive operations. Instead, it is recommended to throttle or debounce the event.
使用 lodash 的 .debounce()
函数的示例.
An example using lodash's .debounce()
function.
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);
}
})
这篇关于每次调整窗口大小然后销毁事件侦听器时如何运行安装的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!