hookehuyr

refactor(StudyCoursePage): 优化顶部区域高度计算逻辑

使用 ResizeObserver 替代 setTimeout 监听元素尺寸变化,提高响应速度和准确性。移除不必要的延迟,并在组件卸载时取消监听,避免内存泄漏。
......@@ -8,11 +8,7 @@
<!-- 固定区域:课程封面和标签页 -->
<div class="fixed top-0 left-0 right-0 z-10 top-wrapper bg-white">
<!-- 课程封面区域 -->
<van-image
class="w-full aspect-video object-cover"
:src="course?.coverImage"
:alt="course?.title"
/>
<van-image class="w-full aspect-video object-cover" :src="course?.coverImage" :alt="course?.title" />
<div class="p-4">
<h1 class="text-black text-xl font-bold mb-2">{{ course?.title }}</h1>
<div class="flex items-center text-gray-500 text-sm">
......@@ -38,7 +34,8 @@
</div>
<!-- 滚动区域:详情、目录和互动内容 -->
<div class="overflow-y-auto flex-1" :style="{paddingTop: topWrapperHeight, height: 'calc(100vh - ' + topWrapperHeight + ')'}">
<div class="overflow-y-auto flex-1"
:style="{ paddingTop: topWrapperHeight, height: 'calc(100vh - ' + topWrapperHeight + ')' }">
<!-- 详情区域 -->
<div id="detail" class="py-4 px-4">
<div class="text-gray-700 text-sm leading-relaxed" v-html="course?.description"></div>
......@@ -50,8 +47,12 @@
<!-- 目录区域 -->
<div id="catalog" class="py-4">
<div class="space-y-4">
<div v-for="(lesson, index) in course?.lessons" :key="index" @click="router.push(`/studyDetail/${lesson.id}`)" class="bg-white p-4 cursor-pointer hover:bg-gray-50 transition-colors border-b border-gray-200 relative">
<div v-if="lesson.progress > 0 && lesson.progress < 100" class="absolute top-2 right-2 px-2 py-1 bg-green-100 text-green-600 text-xs rounded">上次看到</div>
<div v-for="(lesson, index) in course?.lessons" :key="index"
@click="router.push(`/studyDetail/${lesson.id}`)"
class="bg-white p-4 cursor-pointer hover:bg-gray-50 transition-colors border-b border-gray-200 relative">
<div v-if="lesson.progress > 0 && lesson.progress < 100"
class="absolute top-2 right-2 px-2 py-1 bg-green-100 text-green-600 text-xs rounded">
上次看到</div>
<div class="text-black text-base font-medium mb-2">{{ lesson.title }}</div>
<div class="flex items-center text-sm text-gray-500">
<span>视频</span>&nbsp;
......@@ -105,17 +106,21 @@ const topWrapperHeight = ref(0);
// 计算topWrapperHeight的函数
const updateTopWrapperHeight = () => {
setTimeout(() => {
nextTick(() => {
const topWrapper = document.querySelector('.top-wrapper');
if (topWrapper) {
// 确保在DOM更新后获取正确的高度
requestAnimationFrame(() => {
topWrapperHeight.value = `${topWrapper.offsetHeight}px`;
});
}
});
}, 500);
nextTick(() => {
const topWrapper = document.querySelector('.top-wrapper');
if (topWrapper) {
// 使用 ResizeObserver 监听元素尺寸变化
const resizeObserver = new ResizeObserver(() => {
topWrapperHeight.value = `${topWrapper.offsetHeight}px`;
});
resizeObserver.observe(topWrapper);
// 组件卸载时取消监听
onUnmounted(() => {
resizeObserver.disconnect();
});
}
});
};
// 初始化时计算topWrapperHeight
......