vue touch实现上拉
Vue 实现上拉加载功能
使用 @touch 事件监听
通过监听 touchstart、touchmove、touchend 事件实现上拉加载。在 Vue 组件的 methods 中定义相关事件处理函数。
export default {
data() {
return {
startY: 0,
moveY: 0,
loading: false
}
},
methods: {
handleTouchStart(e) {
this.startY = e.touches[0].clientY
},
handleTouchMove(e) {
this.moveY = e.touches[0].clientY
const scrollTop = document.documentElement.scrollTop || document.body.scrollTop
const clientHeight = document.documentElement.clientHeight
const scrollHeight = document.documentElement.scrollHeight
if (scrollTop + clientHeight >= scrollHeight - 50 && this.moveY < this.startY) {
this.loadMore()
}
},
loadMore() {
if (this.loading) return
this.loading = true
// 执行加载数据操作
// 数据加载完成后设置 this.loading = false
}
},
mounted() {
window.addEventListener('touchstart', this.handleTouchStart)
window.addEventListener('touchmove', this.handleTouchMove)
},
beforeDestroy() {
window.removeEventListener('touchstart', this.handleTouchStart)
window.removeEventListener('touchmove', this.handleTouchMove)
}
}
使用第三方库
better-scroll 是一个常用的滚动库,可以方便实现上拉加载功能。
安装 better-scroll:
npm install better-scroll --save
在 Vue 组件中使用:
import BScroll from 'better-scroll'
export default {
data() {
return {
scroll: null,
loading: false
}
},
mounted() {
this.initScroll()
},
methods: {
initScroll() {
this.scroll = new BScroll(this.$refs.wrapper, {
pullUpLoad: true,
click: true
})
this.scroll.on('pullingUp', () => {
this.loadMore()
})
},
loadMore() {
if (this.loading) return
this.loading = true
// 执行加载数据操作
// 数据加载完成后调用 this.scroll.finishPullUp()
// 并设置 this.loading = false
}
}
}
使用 Intersection Observer API
现代浏览器支持的 Intersection Observer API 可以实现元素可见性检测。
export default {
data() {
return {
loading: false,
observer: null
}
},
mounted() {
this.initObserver()
},
methods: {
initObserver() {
const options = {
root: null,
rootMargin: '0px',
threshold: 0.1
}
this.observer = new IntersectionObserver((entries) => {
if (entries[0].isIntersecting) {
this.loadMore()
}
}, options)
this.observer.observe(this.$refs.trigger)
},
loadMore() {
if (this.loading) return
this.loading = true
// 执行加载数据操作
// 数据加载完成后设置 this.loading = false
}
},
beforeDestroy() {
this.observer.disconnect()
}
}
样式处理
为上拉加载添加加载提示样式:
<div class="load-more" v-if="loading">
加载中...
</div>
<style>
.load-more {
text-align: center;
padding: 10px;
color: #999;
}
</style>
以上方法可以根据项目需求选择合适的方式实现上拉加载功能。原生 touch 事件适合简单场景,better-scroll 提供更丰富的功能,Intersection Observer 则更现代化且性能更好。







