hookehuyr

feat(首页): 添加轮播滚动监听以同步底部指示器

在首页轮播组件中添加滚动事件监听,当用户手动滑动时同步更新底部指示器位置。通过计算滚动位置与容器宽度的比例确定当前页索引,并确保索引值在有效范围内。
1 <!-- 1 <!--
2 * @Date: 2025-03-20 19:55:21 2 * @Date: 2025-03-20 19:55:21
3 * @LastEditors: hookehuyr hookehuyr@gmail.com 3 * @LastEditors: hookehuyr hookehuyr@gmail.com
4 - * @LastEditTime: 2025-11-11 17:18:13 4 + * @LastEditTime: 2025-12-04 16:15:23
5 * @FilePath: /mlaj/src/views/HomePage.vue 5 * @FilePath: /mlaj/src/views/HomePage.vue
6 * @Description: 美乐爱觉教育首页组件 6 * @Description: 美乐爱觉教育首页组件
7 * 7 *
...@@ -642,6 +642,44 @@ onMounted(async () => { ...@@ -642,6 +642,44 @@ onMounted(async () => {
642 642
643 // 获取最新活动(外部接口) 643 // 获取最新活动(外部接口)
644 await fetchExternalActivities() 644 await fetchExternalActivities()
645 +
646 + // 监听轮播容器的滚动,手动滑动时同步底部指示器
647 + if (carouselRef.value) {
648 + /**
649 + * @description 根据滚动位置同步当前轮播索引
650 + * @returns {void}
651 + * 注释:通过容器 scrollLeft 与容器宽度计算当前页,向最近页取整。
652 + */
653 + const syncCurrentSlide = () => {
654 + const container = carouselRef.value
655 + const total = goodCourses.value.slice(0, 4).length
656 + if (!container || total === 0) return
657 + const slideWidth = container.offsetWidth
658 + if (slideWidth === 0) return
659 + const rawIndex = container.scrollLeft / slideWidth
660 + const idx = Math.round(rawIndex)
661 + const bounded = Math.min(Math.max(idx, 0), total - 1)
662 + currentSlide.value = bounded
663 + }
664 +
665 + /**
666 + * @description 轮播滚动事件处理(被动监听)
667 + * @returns {void}
668 + * 注释:在用户手动滑动时触发,调用同步函数更新指示器位置。
669 + */
670 + const handleCarouselScroll = () => {
671 + syncCurrentSlide()
672 + }
673 +
674 + carouselRef.value.addEventListener('scroll', handleCarouselScroll, { passive: true })
675 +
676 + // 在卸载时移除监听
677 + onUnmounted(() => {
678 + if (carouselRef.value) {
679 + carouselRef.value.removeEventListener('scroll', handleCarouselScroll)
680 + }
681 + })
682 + }
645 }) 683 })
646 684
647 onUnmounted(() => { 685 onUnmounted(() => {
......