vue 实现下拉刷新
Vue 实现下拉刷新的方法
使用第三方库(如vue-pull-refresh)
安装vue-pull-refresh库:
npm install vue-pull-refresh --save
在组件中引入并使用:
import VuePullRefresh from 'vue-pull-refresh'
export default {
components: {
VuePullRefresh
},
methods: {
onRefresh() {
// 刷新数据逻辑
setTimeout(() => {
this.$refs.pullRefresh.forceUpdate()
}, 1000)
}
}
}
模板部分:
<vue-pull-refresh ref="pullRefresh" @refresh="onRefresh">
<!-- 内容区域 -->
</vue-pull-refresh>
原生实现方案
监听touch事件实现下拉刷新:

data() {
return {
startY: 0,
distance: 0,
isLoading: false
}
},
methods: {
touchStart(e) {
this.startY = e.touches[0].pageY
},
touchMove(e) {
const touchY = e.touches[0].pageY
this.distance = touchY - this.startY
if (this.distance > 0 && window.scrollY <= 0) {
e.preventDefault()
}
},
touchEnd() {
if (this.distance > 100 && !this.isLoading) {
this.isLoading = true
this.refreshData()
}
this.distance = 0
},
refreshData() {
// 数据刷新逻辑
setTimeout(() => {
this.isLoading = false
}, 1000)
}
}
模板部分:
<div
@touchstart="touchStart"
@touchmove="touchMove"
@touchend="touchEnd"
>
<div class="refresh-container" :style="{ transform: `translateY(${distance}px)` }">
<div v-if="isLoading">加载中...</div>
<!-- 内容区域 -->
</div>
</div>
使用better-scroll库
安装better-scroll:
npm install better-scroll --save
实现代码:

import BScroll from 'better-scroll'
export default {
mounted() {
this.initScroll()
},
methods: {
initScroll() {
this.scroll = new BScroll(this.$refs.wrapper, {
pullDownRefresh: {
threshold: 50,
stop: 20
},
click: true
})
this.scroll.on('pullingDown', () => {
this.refreshData()
})
},
refreshData() {
// 异步获取数据
setTimeout(() => {
this.scroll.finishPullDown()
this.scroll.refresh()
}, 1000)
}
}
}
模板部分:
<div ref="wrapper" class="wrapper">
<div class="content">
<!-- 下拉刷新提示 -->
<div class="pull-down-refresh">下拉刷新</div>
<!-- 内容区域 -->
</div>
</div>
样式处理
为原生实现添加基本样式:
.refresh-container {
transition: transform 0.3s;
}
.pull-down-refresh {
text-align: center;
padding: 10px 0;
}
为better-scroll添加样式:
.wrapper {
height: 100vh;
overflow: hidden;
}
以上方法可根据项目需求选择合适方案,第三方库实现更简单快捷,原生实现更灵活可控。






