uni-app小程序左右滑动切换内容
效果图如下:
代码如下:
<template>
<view class="mains" :style="{
transform: 'translateX('+ moveX +'px)',
transition: transition
}" @touchstart="start" @touchend="end" @touchmove="move">
{{nameList[curindex].name}}
</view>
</template>
<script>
export default {
data() {
return {
startData: {
clientX: 0,
clientY: 0
},
curindex: 0,
moveX: 0,
touch: {},
nameList: [{
name: '内容1'
},
{
name: '内容2'
},
{
name: '内容3'
}
],
}
},
methods: {
start(e) {
this.transition = '.1s'
this.startData.clientX = e.changedTouches[0].clientX;
this.startData.clientY = e.changedTouches[0].clientY;
},
end(e) {
this.moveX = 0;
this.transition = '.5s'
const subX = e.changedTouches[0].clientX - this.startData.clientX;
const subY = e.changedTouches[0].clientY - this.startData.clientY;
if (subY > 50 || subY < -50) {
console.log('上下滑动')
} else {
if (subX > 100) {
console.log("右滑动")
this.changeCurindex(2)
} else if (subX < -100) {
console.log("左滑动")
this.changeCurindex(1)
}
}
},
// 根据传入参数判断是左滑还是右滑更改下标,1为左滑,2为右滑
changeCurindex(type) {
const listLength = this.nameList.length;
const curindex = this.curindex
if (curindex < listLength) {
switch (type) {
case 1:
if (listLength - curindex == 1) {
this.curindex = this.curindex
} else {
this.curindex++;
}
break;
case 2:
if (this.curindex == 0) {
this.curindex = 0;
} else {
this.curindex--;
}
}
}
},
move(e) {
let touch = e.touches[0];
this.touch = touch;
let data = touch.clientX - this.startData.clientX;
this.moveX = data;
console.log(data, "data")
if (touch.clientX < this.startData.clientX) { //向左移动
if (data < -250) {
data = -250;
}
}
if (touch.clientX < this.startData.clientX) { //向右移动
if (this.moveX == 0) {
data = 0
} else {
if (data > 50) {
data = 50;
}
}
}
}
},
}
</script>
<style>
.mains {
width: 100%;
height: 300px;
line-height: 300px;
background-color: pink;
text-align: center;
}
</style>