// useSwiper.js文件
import { ref, onMounted, onUnmounted } from "vue";
export function useSwiper({tabList, //tab数据curTabId,// 当前tab idcurTabIndex,// 当前tab 索引tabChange,// tab改变事件animation,// 动画animationData,// 动画
}) {let minOffset = ref(50); //最小偏移量,低于这个值不响应滑动处理let maxOffset = ref(200); //最大偏移量,低于这个值不响应滑动处理let minTime = ref(60); // 最小时间,单位:毫秒,低于这个值不响应滑动处理let startX = ref(0); //开始时的X坐标let startY = ref(0); //开始时的Y坐标let startTime = ref(0); //开始时的毫秒数function touchStart(e) {startX.value = e.touches[0].pageX; // 获取触摸时的x坐标startY.value = e.touches[0].pageY; // 获取触摸时的y坐标startTime.value = new Date().getTime(); //获取毫秒数}function touchMove(e) {animation.translateY(20).step();animationData.value = animation.export();setTimeout(() => {animation.translateY(0).step();animationData.value = animation.export();}, 150);}function touchCancel(e) {startX.value = 0; //开始时的X坐标startY.value = 0; //开始时的Y坐标startTime.value = 0; //开始时的毫秒数}function touchEnd(e) {var endX = e.changedTouches[0].pageX;var endY = e.changedTouches[0].pageY;var touchTime = new Date().getTime() - startTime.value; //计算滑动时间//开始判断//1.判断时间是否符合if (touchTime >= minTime.value) {//2.判断偏移量:分X、Yvar xOffset = endX - startX.value;var yOffset = endY - startY.value;if (Math.abs(xOffset) >= Math.abs(yOffset) &&Math.abs(xOffset) >= minOffset.value &&Math.abs(yOffset) <= 50 &&Math.abs(xOffset) / Math.abs(yOffset) > 3) {//左右滑动console.log("滑动");if (xOffset < 0) {// console.log('向左滑动')if (curTabIndex.value + 1 < tabList.value.length) {curTabIndex.value++;} else return;} else {// console.log('向右滑动')if (curTabIndex.value > 0) {curTabIndex.value--;} else return;}curTabId.value = tabList.value[curTabIndex.value].id;tabChange();}} else {// console.log('滑动时间过短', touchTime)}}return { touchStart, touchMove, touchCancel, touchEnd };
}
页面使用示例:
// vue页面
<template><div@touchstart="touchStart"@touchmove="touchMove"@touchend="touchEnd"@touchcancel="touchCancel":animation="animationData">// 滑动内容</div>
</template><script setup>import { useSwiper } from "@/utils/useSwiper";const tabList = reactive([{name: "新闻",id: '101',index: 0,},{name: "动漫",id: '102',index: 1,},]);let curTabId = ref(tabList[0].id); // 当前tab的idlet curTabIndex = ref(tabList[0].index); // 当前tab的索引let animation = reactive(uni.createAnimation()); // uni动画(选用)let animationData = ref({}); // 动画(选用)const { touchStart, touchMove, touchEnd, touchCancel } = useSwiper({tabList,curTabId,curTabIndex,tabChange,animation,animationData,});// tab切换事件function tabChange(item) {// do something}
</script>