记:uniapp不使用swiper实现左右滑动效果

227 阅读1分钟
<template>
    <view class="data_list" @touchstart="touchStart" @touchend="touchEnd" :animation="animationData">
	<view class="" v-for="item in 120">
				AAA
	</view>
    </view>
</template>


```js
<script>
	export default {
		data() {
			return {
				startX: 0,
				startY: 0,
				animationData: {}, // 动画
			}
		},
		onLoad() {

			// 创建动画实例
			this.animation = uni.createAnimation({
				timingFunction: 'ease',
				duration: 120
			})
		},
		methods: {
			touchStart(event) {
				this.startX = event.touches[0].pageX;
				this.startY = event.touches[0].pageY;

			},
			touchEnd(event) {
				let deltaX = event.changedTouches[0].pageX - this.startX;
				let deltaY = event.changedTouches[0].pageY - this.startY;
				if (Math.abs(deltaX) > Math.abs(deltaY) && Math.abs(deltaX) > 60) {
					if (deltaX < 0) { //往左
						this.getRight()
					} else if (deltaX > 0) { //往右
						this.getLeft()
					} else { // 挪动距离0

					}
				} else {

				}
			},
			getRight() {
				// 动画:左出右进
				this.animation.translateX('-100%').step()
					.opacity(0).step({
						duration: 10
					})
					.translateX('100%').step({
						duration: 10
					})
					.translateX(0).opacity(1).step()

				this.animationData = this.animation.export()
				setTimeout(() => {
					this.animationData = {}
				}, 250)
			},
			getLeft() {
				// 动画:右出左进
				this.animation.translateX('100%').step() //先横向向右移至100%,即整块移没
					.opacity(0).step({ //再使滑块部分透明
						duration: 10
					})
					.translateX('-100%').step({ //然后趁透明横向向左移至-100%
						duration: 10
					}).translateX(0).opacity(1).step() //接着横向向右移动至初始位置并恢复透明度

				this.animationData = this.animation.export()
				// 为避免uniapp动画只有第一次生效,必须延迟删除动画实例数据
				setTimeout(() => {
					this.animationData = {}
				}, 250)
			},
		
			
		},
		

	}
</script>