1、定义基础属性:
scroll_load: { top: 0, startY: 0, touching: false, state: 0, scrolltop: true, },
2、加上监听:
vue自带的标签属性:
@touchstart="touchStart($event)"
@touchmove="touchMove($event)"
@touchend="touchEnd($event)"
3、绑定你需要实现阻尼滑动的dom元素的样式:
为了实现阻尼效果,我们可以根据手指下滑的距离来动态设置元素的padding-top值,让它实现向下滑动。
vue动态绑定样式的方法:(注:带有-的属性,如:padding-top,需要改变为驼峰命名方式如:paddingTop)
v-bind:style="{ paddingTop: scrollerheight }"
(注:scrollerheight 不能定义在data中,需要通过compute访问)
scrollerheight: function scrollerheight() {
return this.scroll_load.top.toString() + 'px';
}
4、js部分:
注:下面的state对应了三个状态(1:滑动状态, 2:到达阀值状态 , 3:正在刷新)和一个初始状态,如何运用这三个状态去实现你想要的效果就各凭本事了
touchStart: function touchStart(e) { // e代表该事件对象,e.targetTouches[0].pageY可以拿到手指 按下的 y轴点 this.scroll_load.startY = e.targetTouches[0].pageY; // 开启下拉刷新状态 this.scroll_load.touching = true; this.scroll_load.state = 1; console.log('touchStart'); }, touchMove: function touchMove(e) { //这个 touchMove,只要页面在动都会发生的,所以 touching就起作用了 // 如果 touching为false,说明这个正在移动的页面不是我们想要的下拉刷新,有可能是用户随意拉了一下页面而已,或者其他 if(!this.scroll_load.touching) return; // 获取移动的距离 var diff = e.targetTouches[0].pageY - this.scroll_load.startY; //判断是向上拉还是向下拉 if(diff >0) { e.preventDefault(); } else { return; } //这个this.top要对应绑定到该元素的transform: translateY(+top+ 'px')上,不然是无法拉动的 // 因此这里还要对偏移高度做一下处理,直接设置diff +(this.state === 2 ? 40 : 0) 太快了,因为拉取幅度太大 // 让diff*0.25这样子就差不多了 this.scroll_load.top = Math.floor(diff*0.25); if(this.scroll_load.top >= 40){ this.scroll_load.state = 2; //释放刷新。。。。。。2 this.scroll_load.top = 40; } else { this.scroll_load.state = 1; // 开始滑动。。。。。。1 } }, touchEnd: function touchEnd(e) { this.scroll_load.touching = false; if(this.scroll_load.state === 4) { return; } // 判断抬起时的高度,是大于40 就开启刷新 if(this.scroll_load.top >= 40) { this.refresh(); } else { this.scroll_load.state = 0; this.scroll_load.top = 0; } console.log("touchEnd") }, refresh: function refresh(){ console.log("refresh"); var that = this; this.scroll_load.state = 3; // 正在刷新。。。。。。3 // 在这下面实现你要的刷新方法,查询数据,记得将top、state重置为0 } },