vue实现下拉刷新
Vue 实现下拉刷新功能
使用第三方库(推荐)
安装 vue-pull-refresh 库:
npm install vue-pull-refresh --save
在组件中使用:
<template>
<pull-refresh :on-refresh="onRefresh">
<!-- 你的列表内容 -->
<div v-for="item in list" :key="item.id">{{ item.text }}</div>
</pull-refresh>
</template>
<script>
import PullRefresh from 'vue-pull-refresh'
export default {
components: {
PullRefresh
},
data() {
return {
list: [] // 你的数据列表
}
},
methods: {
onRefresh() {
return new Promise((resolve) => {
// 模拟异步请求
setTimeout(() => {
// 更新数据
this.list = [...this.getNewData(), ...this.list]
resolve()
}, 1000)
})
},
getNewData() {
// 获取新数据的逻辑
return [...]
}
}
}
</script>
原生实现方案
监听 touch 事件实现基础下拉刷新:
<template>
<div class="pull-refresh" @touchstart="touchStart" @touchmove="touchMove" @touchend="touchEnd">
<div class="refresh-tip" :style="{ height: pullHeight + 'px' }">
{{ refreshText }}
</div>
<div class="content">
<!-- 你的列表内容 -->
</div>
</div>
</template>
<script>
export default {
data() {
return {
startY: 0,
currentY: 0,
pullHeight: 0,
isRefreshing: false,
maxPullHeight: 80
}
},
computed: {
refreshText() {
if (this.isRefreshing) return '加载中...'
return this.pullHeight > this.maxPullHeight ? '释放刷新' : '下拉刷新'
}
},
methods: {
touchStart(e) {
this.startY = e.touches[0].pageY
},
touchMove(e) {
if (this.isRefreshing) return
this.currentY = e.touches[0].pageY
const scrollTop = document.documentElement.scrollTop || document.body.scrollTop
if (scrollTop <= 0) {
const distance = this.currentY - this.startY
if (distance > 0) {
e.preventDefault()
this.pullHeight = Math.min(distance, this.maxPullHeight * 2)
}
}
},
touchEnd() {
if (this.isRefreshing) return
if (this.pullHeight > this.maxPullHeight) {
this.isRefreshing = true
this.refreshData().finally(() => {
this.isRefreshing = false
this.pullHeight = 0
})
} else {
this.pullHeight = 0
}
},
refreshData() {
return new Promise(resolve => {
// 你的数据刷新逻辑
setTimeout(resolve, 1000)
})
}
}
}
</script>
<style>
.pull-refresh {
position: relative;
}
.refresh-tip {
position: absolute;
width: 100%;
display: flex;
align-items: center;
justify-content: center;
overflow: hidden;
top: -100%;
}
</style>
移动端优化建议
添加过渡动画提升用户体验:
.refresh-tip {
transition: height 0.3s ease;
}
防止页面滚动与下拉刷新冲突:

touchMove(e) {
if (this.isRefreshing) return
if (this.pullHeight > 0) {
e.preventDefault()
}
// 其他逻辑...
}
注意事项
- 在移动端使用时需要确保 meta 标签正确设置 viewport
- 下拉刷新通常需要与上拉加载更多配合使用
- 考虑添加加载动画提升用户体验
- 在数据加载完成前禁用重复触发
两种方案各有优劣,第三方库实现更简单功能更完善,原生实现更灵活可控。根据项目需求选择合适方案。






