微信小程序监听页面滑动手势
2024-08-01 13:43 阅读(280)

功能背景是类似小红书顶部Tab,页面中左右滑动时,顶部Tab自动切换。


页面结构:

<Tab  id="tabComponent" />
<scroll-view bindtouchstart="touchStart" bindtouchmove="touchMove" bindtouchend="touchEnd">

</scroll-view>

主要思路就是:记录滑动位置,滑动结束调用子组件方法,设置当前选中Tab以及后续数据请求操作。


selectComponent直接根据id找到子组件,然后直接调用子组件中提供的setActiveTab方法。


代码实现:

    // 监听页面滑动手势开始
    touchStartX:0,//记录滑动开始位置
    touchEndX:0,//记录滑动结束位置
    touchStart(e){
        const x = e.touches[0].pageX;
        // console.log('滑动开始',x);
        this.touchStartX = x;
    },
    touchMove(e){
        const x = e.touches[0].pageX;
        // console.log('滑动中',x);
        this.touchEndX = x;
    },
    touchEnd(e){
        // console.log('滑动结束',e)
        const {touchStartX,touchEndX} = this;
        const tabComponent = this.selectComponent('#tabComponent');
        if(touchStartX < touchEndX - 50){
            // 向右滑动了
            tabComponent.setActiveTab(-1);
        }
        if(touchStartX > touchEndX + 50){
            // 向左滑动了
            tabComponent.setActiveTab(1);
        }
    },
    // 监听页面滑动手势结束