vue 实现滑动加载
实现滑动加载的基本思路
滑动加载通常通过监听滚动事件,判断是否滚动到页面底部来触发数据加载。Vue中可以利用v-infinite-scroll指令或手动监听滚动事件实现。
使用v-infinite-scroll指令
Element UI等库提供了v-infinite-scroll指令,简化实现:
<template>
<div v-infinite-scroll="loadMore" :infinite-scroll-disabled="busy" infinite-scroll-distance="10">
<div v-for="item in items" :key="item.id">{{ item.content }}</div>
</div>
</template>
<script>
export default {
data() {
return {
items: [],
busy: false,
page: 1
}
},
methods: {
loadMore() {
this.busy = true
fetchData(this.page).then(newItems => {
this.items = [...this.items, ...newItems]
this.page++
this.busy = false
})
}
}
}
</script>
手动实现滚动监听
没有使用UI库时,可以手动实现:
<template>
<div class="scroll-container" @scroll="handleScroll">
<div v-for="item in items" :key="item.id">{{ item.content }}</div>
<div v-if="loading">Loading...</div>
</div>
</template>
<script>
export default {
data() {
return {
items: [],
loading: false,
page: 1,
noMore: false
}
},
methods: {
handleScroll(e) {
const container = e.target
const bottomOffset = container.scrollHeight - container.scrollTop - container.clientHeight
if (bottomOffset < 50 && !this.loading && !this.noMore) {
this.loadMore()
}
},
loadMore() {
this.loading = true
fetchData(this.page).then(newItems => {
if (newItems.length === 0) {
this.noMore = true
} else {
this.items = [...this.items, ...newItems]
this.page++
}
this.loading = false
})
}
}
}
</script>
<style>
.scroll-container {
height: 500px;
overflow-y: auto;
}
</style>
性能优化建议
添加防抖避免频繁触发滚动事件:
import { debounce } from 'lodash'
methods: {
handleScroll: debounce(function(e) {
// 滚动处理逻辑
}, 200)
}
使用Intersection Observer API实现更高效的检测:
mounted() {
const observer = new IntersectionObserver((entries) => {
if (entries[0].isIntersecting && !this.loading && !this.noMore) {
this.loadMore()
}
})
observer.observe(this.$refs.observerTarget)
}
注意事项
确保在组件销毁时移除事件监听:
beforeDestroy() {
window.removeEventListener('scroll', this.handleScroll)
}
分页加载时需要考虑数据去重问题,避免重复加载相同数据。







