歌手列表快速导航入口

该文章描述了一个Vue组件,用于根据数据动态生成快捷列表,并通过触摸事件处理切换组的功能。组件利用计算属性获取标题,使用`@touchstart.stop.prevent`防止事件冒泡并阻止默认行为。在触摸开始和移动时,计算新的索引以实现平滑滚动到目标元素。同时,文章还包含了错误检查和边界值处理。
摘要由CSDN通过智能技术生成

1.获取每个组的标题构成shortcutList,即currentIndex的响应式数据,用钩子函数封装

export default function usrShortcut(props) {
    const shortcutList = computed(() => {
        return props.data.map((group) => {
            return group.title
        })
    })
    return { 
        shortcutList 
    }
}

2.实现点击切换对应的组
(1)绑定事件,阻止冒泡,阻止默认行为

@touchstart.stop.prevent="onShortcutTouchStart"

(2)把索引绑定到data-index,使用BetterScroll中的scrollToElement()方法

function onShortcutTouchStart (e) {
        const anchorIndex = parentInt(e.target.dataset.index)
		const targetEL = groupRef.value.children[index]
        const scroll = scrollRef.value.scroll
        scroll.scrollToElement(targetEL, 0)

    }

3.实现手指拖动切换对应的组
利用Touchstart的第一个纵坐标减去TouchMove的第一个纵坐标的插值加上初始索引delta

function onShortcutTouchMove (e) {
        touch.y2 = e.touches[0].pageY
        const delta = (touch.y2 - touch.y1)/ ANCHOR_HEIGHT | 0
        const anchorIndex = touch.anchorIndex + delta

        scrollTo(anchorIndex)
    }

封装函数

function scrollTo(index) {
        if (isNaN(index)) {
            return
        }
        index = Math.max(0, Math.min(shortcutList.value.length - 1, index))
        const targetEL = groupRef.value.children[index]
        const scroll = scrollRef.value.scroll
        scroll.scrollToElement(targetEL, 0)
    }

完整代码

import { ref, computed } from "vue";

export default function usrShortcut(props) {
    const ANCHOR_HEIGHT = 18
    const scrollRef = ref(null)
    
    const shortcutList = computed(() => {
        return props.data.map((group) => {
            return group.title
        })
    })

    const touch = {}

    function onShortcutTouchStart (e) {
        const anchorIndex = parentInt(e.target.dataset.index)
        touch.y1 = e.touches[0].pageY
        touch.anchorIndex = anchorIndex

        scrollTo(anchorIndex)
    }

    function onShortcutTouchMove (e) {
        touch.y2 = e.touches[0].pageY
        const delta = (touch.y2 - touch.y1)/ ANCHOR_HEIGHT | 0
        const anchorIndex = touch.anchorIndex + delta

        scrollTo(anchorIndex)
    }

    function scrollTo(index) {
        if (isNaN(index)) {
            return
        }
        index = Math.max(0, Math.min(shortcutList.value.length - 1, index))
        const targetEL = groupRef.value.children[index]
        const scroll = scrollRef.value.scroll
        scroll.scrollToElement(targetEL, 0)
    }

    return { 
        shortcutList ,
        scrollRef,
        onShortcutTouchStart,
        onShortcutTouchMove
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值