hookehuyr

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

在组件挂载时添加窗口大小变化监听,并在DOM更新后延迟计算topWrapperHeight,以确保获取正确的高度。同时,在组件卸载时移除所有相关事件监听器,避免内存泄漏。
...@@ -103,6 +103,37 @@ useTitle('课程详情'); ...@@ -103,6 +103,37 @@ useTitle('课程详情');
103 const activeTab = ref('detail'); 103 const activeTab = ref('detail');
104 const topWrapperHeight = ref(0); 104 const topWrapperHeight = ref(0);
105 105
106 +// 计算topWrapperHeight的函数
107 +const updateTopWrapperHeight = () => {
108 + setTimeout(() => {
109 + nextTick(() => {
110 + const topWrapper = document.querySelector('.top-wrapper');
111 + if (topWrapper) {
112 + // 确保在DOM更新后获取正确的高度
113 + requestAnimationFrame(() => {
114 + topWrapperHeight.value = `${topWrapper.offsetHeight}px`;
115 + });
116 + }
117 + });
118 + }, 300);
119 +};
120 +
121 +// 初始化时计算topWrapperHeight
122 +onMounted(() => {
123 + // 添加滚动监听
124 + window.addEventListener('scroll', handleScroll);
125 + // 添加窗口大小变化监听
126 + window.addEventListener('resize', updateTopWrapperHeight);
127 + // 确保在组件挂载后计算高度
128 + updateTopWrapperHeight();
129 +});
130 +
131 +// 在组件卸载时移除监听器
132 +onUnmounted(() => {
133 + window.removeEventListener('scroll', handleScroll);
134 + window.removeEventListener('resize', updateTopWrapperHeight);
135 +});
136 +
106 // 处理滚动事件 137 // 处理滚动事件
107 const handleScroll = () => { 138 const handleScroll = () => {
108 const detailElement = document.getElementById('detail'); 139 const detailElement = document.getElementById('detail');
...@@ -138,23 +169,6 @@ const handleTabChange = (name) => { ...@@ -138,23 +169,6 @@ const handleTabChange = (name) => {
138 }); 169 });
139 }; 170 };
140 171
141 -onMounted(() => {
142 - nextTick(() => {
143 - const topWrapper = document.querySelector('.top-wrapper');
144 - if (topWrapper) {
145 - topWrapperHeight.value = topWrapper.clientHeight + 'px';
146 - }
147 -
148 - // 添加滚动监听
149 - window.addEventListener('scroll', handleScroll);
150 - });
151 -});
152 -
153 -// 在组件卸载时移除滚动监听
154 -onUnmounted(() => {
155 - window.removeEventListener('scroll', handleScroll);
156 -});
157 -
158 // 课程数据 172 // 课程数据
159 const course = ref({ 173 const course = ref({
160 title: '开学礼·止的智慧·心法老师·20241001', 174 title: '开学礼·止的智慧·心法老师·20241001',
......