<template>
<div>
<button @click="debouncedClick">点击按钮</button>
</div>
</template>
<script>
export default {
data() {
return {
debounceTimer: null,
throttleTimer: null,
// 假设的数据
dataToUpdate: ''
};
},
mounted() {
window.addEventListener('scroll', this.throttledScroll);
},
methods: {
updateData() {
// 这里写数据更新的逻辑
this.dataToUpdate = '更新后的数据';
},
debouncedClick() {
if (this.debounceTimer) {
clearTimeout(this.debounceTimer);
}
this.debounceTimer = setTimeout(() => {
this.updateData();
}, 300);
},
adjustLayout() {
// 这里写页面布局调整的逻辑
console.log('页面布局调整');
},
throttledScroll() {
if (!this.throttleTimer) {
this.adjustLayout();
this.throttleTimer = setTimeout(() => {
this.throttleTimer = null;
}, 300);
}
}
},
beforeDestroy() {
window.removeEventListener('scroll', this.throttledScroll);
if (this.debounceTimer) {
clearTimeout(this.debounceTimer);
}
if (this.throttleTimer) {
clearTimeout(this.throttleTimer);
}
}
};
</script>
组件销毁时的清理说明
- 事件监听器清理:在
beforeDestroy
钩子函数中,通过window.removeEventListener('scroll', this.throttledScroll)
移除窗口滚动事件监听器,避免在组件销毁后仍然执行相关回调函数,从而导致内存泄漏。
- 定时器清理:在
beforeDestroy
钩子函数中,检查debounceTimer
和throttleTimer
是否存在,如果存在则使用clearTimeout
清除定时器,防止定时器在组件销毁后继续运行占用内存。