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爲獲取數據方法,可根據自身來更改以上代碼
寫這篇文章爲了記錄,剛學,勿噴。