hookehuyr

refactor(StudyCoursePage): 优化topWrapperHeight的计算和事件监听

在组件挂载时添加窗口大小变化监听,并在DOM更新后延迟计算topWrapperHeight,以确保获取正确的高度。同时,在组件卸载时移除所有相关事件监听器,避免内存泄漏。
......@@ -103,6 +103,37 @@ useTitle('课程详情');
const activeTab = ref('detail');
const topWrapperHeight = ref(0);
// 计算topWrapperHeight的函数
const updateTopWrapperHeight = () => {
setTimeout(() => {
nextTick(() => {
const topWrapper = document.querySelector('.top-wrapper');
if (topWrapper) {
// 确保在DOM更新后获取正确的高度
requestAnimationFrame(() => {
topWrapperHeight.value = `${topWrapper.offsetHeight}px`;
});
}
});
}, 300);
};
// 初始化时计算topWrapperHeight
onMounted(() => {
// 添加滚动监听
window.addEventListener('scroll', handleScroll);
// 添加窗口大小变化监听
window.addEventListener('resize', updateTopWrapperHeight);
// 确保在组件挂载后计算高度
updateTopWrapperHeight();
});
// 在组件卸载时移除监听器
onUnmounted(() => {
window.removeEventListener('scroll', handleScroll);
window.removeEventListener('resize', updateTopWrapperHeight);
});
// 处理滚动事件
const handleScroll = () => {
const detailElement = document.getElementById('detail');
......@@ -138,23 +169,6 @@ const handleTabChange = (name) => {
});
};
onMounted(() => {
nextTick(() => {
const topWrapper = document.querySelector('.top-wrapper');
if (topWrapper) {
topWrapperHeight.value = topWrapper.clientHeight + 'px';
}
// 添加滚动监听
window.addEventListener('scroll', handleScroll);
});
});
// 在组件卸载时移除滚动监听
onUnmounted(() => {
window.removeEventListener('scroll', handleScroll);
});
// 课程数据
const course = ref({
title: '开学礼·止的智慧·心法老师·20241001',
......