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
}
}