早段时间手写了一个下拉刷新,记录一下
效果如图
代码如下
<template>
<div>
<div :style="{height:distance + 'px'}" class="pull_refresh d-flex ai-center jc-center">
<p class="text-center text-gray p-2 text" v-if="pullStatus !==2">{{pullTexts[pullStatus]}}</p>
<van-loading size="24px" v-else>{{pullTexts[pullStatus]}}</van-loading>
</div>
<div class="home p-2" @touchstart="touchStart" @touchend="touchEnd" @touchmove="touchMove"></div>
</div>
</template>
<script lang="ts">
import { defineComponent } from "vue";
import { Loading } from "vant";
export default defineComponent({
components: {
[Loading.name]: Loading,
},
data() {
return {
startPosition: 0, // 触摸开始位置
endPosition: 0, // 触摸结束位置
distance: 0, // 下拉距离
pullStatus: 0, // 0下拉即可刷新 1松手即可刷新 2加载中 3加载完毕
pullTexts: ["下拉即可刷新哦~", "松手刷新~", "加载中...", "加载完毕"],
};
},
methods: {
/**
* @see 滑动开始事件
*/
touchStart(e: any) {
this.startPosition = e.touches[0].pageY;
},
/**
* @see 滑动事件
*/
touchMove(e: any) {
// 获取一下当前滚动条的位置
const scrollTop =
document.documentElement.scrollTop || document.body.scrollTop;
// 滚动条在顶部的时候才认定为下拉操作
if (scrollTop < 1) {
// 获取开始和结束位置的 差
let distance = e.touches[0].pageY - this.startPosition;
// 差值大于0 代表从上往下滑,才允许操作
if (distance > 0) {
// 阻止默认事件,极其重要,不加的话部分浏览器 页面无法滑动 or 滑动时闪烁 or....,可以使用移动端微信浏览器测试效果
e.preventDefault();
// 判断移动一个距离,超过这个距离松手 执行 刷新操作
if (distance > 70) {
if (distance !== 70) {
// 改变状态,设置下拉最大距离
this.pullStatus = 1;
this.distance = 70;
}
} else {
// 将计算得来的差值赋值,以使页面向下移动
this.pullStatus = 0;
this.distance = distance;
}
}
}
},
/**
* @see 滑动结束事件
*/
touchEnd(e: any) {
const scrollTop =
document.documentElement.scrollTop || document.body.scrollTop;
// 在结束时,需要判断一下状态和下拉的距离,符合要求才执行下拉的操作
if (scrollTop <= 1 && this.distance >= 70) {
this.pullStatus = 2;
// 定时器模拟调用接口刷新页面
setTimeout(() => {
// 刷新成功
this.distance = 0;
this.pullStatus = 3;
}, 3000);
}
},
},
});
</script>
<style lang="scss" scoped>
.home {
height: 100px;
width: 100%;
background: red;
}
</style>