uniapp滑动切换tab

579 阅读1分钟

uniapp滑动切换tab和内容

template

   <template>
       <view class="task" @touchstart.stop="handleTouchstart" @touchend.stop="handleTouchend">
       </view>
   </template>

组件js

data(){
    return{
        tabIndex: -1,
        stateList: [
                {
                        id:-1,
                        name:"全部"
                },{
                        id:0,
                        name:"待付款"
                },{
                        id:1,
                        name:"待发货"
                },{
                        id:2,
                        name:"待收货"
                }
        ],
        startX: 0,
        startY: 0,
        indexs: 0
    }
},
methods: {
    // 获取鼠标、手指初始位置
    handleTouchstart(e) {
            this.startTime = Date.now();
            this.startX = e.changedTouches[0].clientX;
            this.startY = e.changedTouches[0].clientY;
    },
    // 计算鼠标、手指偏移方向
    handleTouchend(e) {
            const endTime = Date.now();
            const length = this.stateList.length - 1;
            const endX = e.changedTouches[0].clientX;
            const endY = e.changedTouches[0].clientY;
            const differ = Math.abs(endY - this.startY);
            const dirvalX = endX - this.startX;
            // 纵轴偏移量不得超过 30,否则默认页面进行滚动操作
            if (differ <= 30) {
                    // 按下时长不得超过 2秒,X轴滑动距离必须大于 40
                    if (endTime - this.startTime > 2000 || Math.abs(dirvalX) <= 40) {
                            return
                    };
                    // 判断滑动方向
                    if (dirvalX > 0) {
                            this.indexs++;
                            if (this.indexs >= length) this.indexs = length-1;
                    } else if (dirvalX < 0){
                            this.indexs--;
                            if (this.indexs < 0) this.indexs = -1;
                    }
                    this.tabIndex = this.indexs
                    //切换的时候调取接口
                    //如果封装成组件把this.indexs $emit出去
            }
    },
}

封装成组件

<template>
	<!-- 屏幕左右滑动切换tabs功能组件 -->
	<view class="tk-screen-scroll" @touchstart.stop="handleTouchstart" @touchend.stop="handleTouchend">
            <slot></slot>
	</view>
</template>