uni-app小程序左右滑动切换内容

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>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值