vue.js - 每次调整窗口大小时如何运行挂载函数然后销毁事件侦听器
问题描述
我有以下挂载的函数,然后我想在每次调整窗口大小时运行它。我还想在事件运行后使用 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)`
})
}
},
解决方案
您可以将函数移动到其中的单独部分,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);
}
})
推荐阅读
- android - 在Android中将图像从文件路径转换为base64对我不起作用
- angularjs - 没有为外部 angularjs 文件动态加载创建范围
- terraform - Terraform:如何获取所有 vnet 详细信息并迭代其子网
- php - 重定向角色时非对象的角色
- python - Python 3.6 API 请求 - JSONDecodeError:预期值:第 1 行第 1 列(字符 0)错误
- java - JSON数组列表解析并在tablayout中显示
- javascript - 当 Ionic 中的输入触发时,关闭 Android 设备中的键盘
- r - 使用 GGPLOT2 显示因子变量之间的关系
- c++ - 信号处理以确保在 C++ 中调用析构函数
- c++ - 如何使用指针找到两个排序数组的并集?