1:在src下创建一个components组件文件 在创建滑动封装组件文件
在文件中封装滑动。
handleTouchstart :手指按下 ,
handleTouchend:手指离开 。
话不多说 拉代码。
<template>
<view
@touchstart="handleTouchstart"
@touchend="handleTouchend">
<slot></slot>
</view>
</template>
<script>
export default {
data(){
return {
//按下的时间
startTime : 0,
//按下的坐标
startX : 0,
startY : 0
}
},
methods:{
//用户按下屏幕
handleTouchstart(event){
// console.log("手指按下屏幕");
// console.log("按下:"+event.changedTouches[0].clientX);
// console.log("按下:"+event.changedTouches[0].clientY);
this.startTime = Date.now();
this.startX = event.changedTouches[0].clientX;
this.startY = event.changedTouches[0].clientY;
},
handleTouchend(event){
// console.log("手指离开屏幕");
// console.log("离开:"+event.changedTouches[0].clientX);
// console.log("离开:"+event.changedTouches[0].clientY);
const endTime = Date.now();
const endX = event.changedTouches[0].clientX;
const endY = event.changedTouches[0].clientY;
//判断按下的时长 2000 = 2s
if(endTime - this.startTime > 2000){
return ;
}
//滑动的方向
let direction = "";
//判断用户滑动的距离 是否合法 合法:判断滑动的方向 ** 距离要加上绝对值
if(Math.abs(endX - this.startX) > 10 && Math.abs(endY - this.startY) < 10){
direction = endX - this.startX>0?"right":"left";
} else {
return ;
}
//console.log(direction)
this.$emit("swiperAction",{direction});
}
}
}
</script>
<style>
</style>
封装后,在所需页面引入组件
import swiperAction from "@/components/swiperAction";
这里我起的名字是swiperAction ,用这个标签包住image图片(注:所需滑动的部分。swiperAction包含标签时,大写需改为小写 中间带杠-)
<swiper-action @swiperAction="handleSwiperAction">
<image mode="widthFix" :src="imgDetail.thumb"></image>
</swiper-action>
handleSwiperAction为自定义方法,附代码(注:写在methods中):
//滑动事件
handleSwiperAction(e){
/**
* 1 用户左滑 imgIndex++
* 2 用户右滑 imgIndex--
* 3 判断 数组是否越界
* 4 左滑 e.diretion === "left" && this.imgIndex < imgList.length - 1
* 5 右滑 e.diretion === "right" && this.imgIndex > 0
*/
const{imgList} = getApp().globalData;
if(e.direction === "left" && this.imgIndex < imgList.length - 1){
//可以进行 左滑 加载下一页
this.imgIndex++;
this.getData();
} else if(e.direction === "right" && this.imgIndex > 0){
// 右滑 加载上一页
this.imgIndex--;
this.getData();
} else {
uni.showToast({
title:"暂无数据",
icon:"none"
})
}
// console.log(e)
}
其中 direction是组件中返回的值。this.imgIndex是当前图片的索引,getData为获取数据方法,可根据自身来更改以上代码