vue滚动实现翻页
Vue 实现滚动翻页的方法
监听滚动事件结合分页加载
在 Vue 组件中监听滚动事件,当滚动到底部时触发数据加载。需要计算滚动位置和容器高度。

<template>
<div class="scroll-container" @scroll="handleScroll">
<div v-for="item in items" :key="item.id">{{ item.content }}</div>
<div v-if="loading">加载中...</div>
</div>
</template>
<script>
export default {
data() {
return {
items: [],
page: 1,
loading: false,
hasMore: true
}
},
methods: {
async loadMore() {
if (this.loading || !this.hasMore) return
this.loading = true
const newItems = await fetchData(this.page)
if (newItems.length) {
this.items.push(...newItems)
this.page++
} else {
this.hasMore = false
}
this.loading = false
},
handleScroll(e) {
const { scrollTop, clientHeight, scrollHeight } = e.target
const bottomReached = scrollTop + clientHeight >= scrollHeight - 50
if (bottomReached) {
this.loadMore()
}
}
},
mounted() {
this.loadMore()
}
}
</script>
<style>
.scroll-container {
height: 500px;
overflow-y: auto;
}
</style>
使用 Intersection Observer API
更现代的解决方案是使用 Intersection Observer API,性能优于滚动事件监听。
<template>
<div class="scroll-container">
<div v-for="item in items" :key="item.id">{{ item.content }}</div>
<div ref="sentinel" v-if="hasMore">
<span v-if="loading">加载中...</span>
</div>
</div>
</template>
<script>
export default {
data() {
return {
items: [],
page: 1,
loading: false,
hasMore: true,
observer: null
}
},
methods: {
async loadMore() {
if (this.loading || !this.hasMore) return
this.loading = true
const newItems = await fetchData(this.page)
if (newItems.length) {
this.items.push(...newItems)
this.page++
} else {
this.hasMore = false
}
this.loading = false
}
},
mounted() {
this.observer = new IntersectionObserver((entries) => {
if (entries[0].isIntersecting) {
this.loadMore()
}
})
this.$nextTick(() => {
this.observer.observe(this.$refs.sentinel)
})
this.loadMore()
},
beforeDestroy() {
this.observer.disconnect()
}
}
</script>
使用第三方库
对于复杂场景,可以考虑使用专门处理无限滚动的库如 vue-infinite-loading。

安装:
npm install vue-infinite-loading
使用示例:
<template>
<div>
<div v-for="item in items" :key="item.id">{{ item.content }}</div>
<infinite-loading @infinite="loadMore" spinner="spiral">
<div slot="no-more">没有更多数据了</div>
<div slot="no-results">没有数据</div>
</infinite-loading>
</div>
</template>
<script>
import InfiniteLoading from 'vue-infinite-loading'
export default {
components: { InfiniteLoading },
data() {
return {
items: [],
page: 1
}
},
methods: {
async loadMore($state) {
try {
const newItems = await fetchData(this.page)
if (newItems.length) {
this.items.push(...newItems)
this.page++
$state.loaded()
} else {
$state.complete()
}
} catch (err) {
$state.error()
}
}
}
}
</script>
性能优化建议
- 使用虚拟滚动技术处理大量数据,如
vue-virtual-scroller - 添加防抖处理滚动事件
- 在组件销毁时移除事件监听器
- 考虑添加加载状态和错误处理
- 对于移动端,注意 touch 事件的处理
以上方法可以根据具体需求选择使用,Intersection Observer 方案在现代浏览器中性能最佳,而第三方库则提供了更多开箱即用的功能。






