移动端左滑右滑组件

很久没发布文章了,一方面工作原因,一方面是惰性开始出来了。希望能继续坚持菜鸡之路。

最近有个需求,移动端有导航,需要左滑右滑的时候就能切换导航,跟轮播一样的效果,但是轮播内容少,而且是一次性加载数据。而需求是很多类型,每个类型有非常多的列表,如果使用轮播,一次性加载数据太多,再加上分页,那就完全行不通。

自己写了个左滑右滑的组件。我一直觉得写组件最重要的就是理解原理和理清思路。

当我们触摸到屏幕的时候,会触发touchStar方法,获取起始的X坐标值startX,在手指移动过程中,会触发touchMove方法,获得手指当前的X坐标值currentX。CurrentX-startX就是移动的距离,让当前父元素相对定位,然后随着移动定位left的值。这样就实现了一个元素左滑右滑的效果。

接着考虑当手指松开的时候触发touchEnd方法,获取endX,endX减去startX或者是移动过程中的距离,大于0就是手指向右滑动,小于0就是向左滑动。然后在结束的时候把相对定位的父元素left变成0.

因为是组件,我们把左滑还是右滑返回,把可能需要用到的移动过程中的距离也返回。最后,我们在移动一点点距离的时候不一定要左滑右滑,所以需要一个最小的滑动距离。


<template>
 <div class="">
   <divclass="touch-movue-left-right"
       @touchstart="touchStart($event)"
       @touchend="touchEnd($event)"
       @touchmove="touchMove($event)"
   :style="{'left': moveMar +'px'}">
   <slot></slot>
   </div>
 </div>
</template>



export default {
 props: ['moveJudge', 'moveDistance','margin'],
 data() {
   return {
     startX: 0,
     moveMar: 0
   }
 },
 components: {},
 mounted() {

 },
 methods: {
   touchStart(e){
     this.startX =e.targetTouches[0].pageX;
   },
   touchMove(e){
     this.moveMar =e.targetTouches[0].pageX - this.startX;
     this.$emit('moveDistance',this.moveMar);
   },
   touchEnd(e){
     if(this.moveMar > (this.margin ||100)){
       this.$emit('moveJudge', 'right');
     }else if(this.moveMar <(-this.margin || -100)){
       this.$emit('moveJudge', 'left');
     }
     this.moveMar = 0;
   },
 }
}



.touch-movue-left-right{
 position: relative;
 width: 100%;
 background: #42b983;
}

可以自己使用一下,顺便提一下,上拉加载下拉刷新之前是分开的,增加了一个一起的,加上左滑右滑,已经发布npm:

https://www.npmjs.com/package/wade-ui

欢迎关注Coding个人笔记 公众号

猜你喜欢

转载自blog.csdn.net/wade3po/article/details/86749791