vue 实现滚动加载
实现滚动加载的基本原理
滚动加载的核心逻辑是监听滚动事件,当用户滚动到页面底部或指定位置时触发数据加载。Vue中可以通过v-infinite-scroll指令或手动监听滚动事件实现。
使用v-infinite-scroll指令
Element UI等库提供了现成的无限滚动指令。安装Element UI后可直接使用:
<template>
<div v-infinite-scroll="loadMore" infinite-scroll-disabled="busy" infinite-scroll-distance="10">
<div v-for="item in list" :key="item.id">{{ item.content }}</div>
</div>
</template>
<script>
export default {
data() {
return {
list: [],
busy: false,
page: 1
}
},
methods: {
loadMore() {
this.busy = true
fetchData(this.page).then(res => {
this.list = this.list.concat(res.data)
this.page++
this.busy = false
})
}
}
}
</script>
手动实现滚动监听
无第三方依赖的纯Vue实现方式:
<template>
<div class="scroll-container" @scroll="handleScroll">
<div v-for="item in items" :key="item.id">{{ item.text }}</div>
<div v-if="loading">加载中...</div>
</div>
</template>
<script>
export default {
data() {
return {
items: [],
loading: false,
page: 1,
hasMore: true
}
},
mounted() {
this.loadData()
},
methods: {
handleScroll(e) {
const { scrollTop, clientHeight, scrollHeight } = e.target
const bottomThreshold = 50 // 距底部50px触发
if (scrollHeight - (scrollTop + clientHeight) < bottomThreshold
&& !this.loading
&& this.hasMore) {
this.loadData()
}
},
async loadData() {
this.loading = true
const newItems = await fetchData(this.page)
this.items = [...this.items, ...newItems]
this.page++
this.hasMore = newItems.length > 0
this.loading = false
}
}
}
</script>
<style>
.scroll-container {
height: 500px;
overflow-y: auto;
}
</style>
性能优化建议
添加防抖避免频繁触发滚动事件
import { debounce } from 'lodash-es'
methods: {
handleScroll: debounce(function(e) {
// 滚动逻辑
}, 200)
}
使用Intersection Observer API实现更高效的检测
mounted() {
const observer = new IntersectionObserver((entries) => {
if (entries[0].isIntersecting && !this.loading && this.hasMore) {
this.loadData()
}
})
observer.observe(this.$refs.observerTarget)
}
注意事项
确保在组件销毁时移除事件监听
beforeDestroy() {
window.removeEventListener('scroll', this.handleScroll)
}
分页加载时需要处理无更多数据的情况

loadData() {
if (!this.hasMore) return
// ...加载逻辑
}






