vue实现滑动加载
滑动加载的实现思路
滑动加载通常通过监听滚动事件,判断是否滚动到页面底部来触发数据加载。Vue中可以通过结合v-for、@scroll事件和计算属性实现。
基础实现方法
监听滚动事件
在包含滚动区域的元素上添加@scroll监听,计算是否触底:
<div class="scroll-container" @scroll="handleScroll">
<div v-for="item in items" :key="item.id">{{ item.content }}</div>
</div>
计算滚动位置
通过比较scrollTop、clientHeight和scrollHeight判断是否触底:
methods: {
handleScroll(e) {
const { scrollTop, clientHeight, scrollHeight } = e.target
if (scrollHeight - scrollTop <= clientHeight + 50) {
this.loadMore()
}
}
}
使用Intersection Observer API
更现代的实现方式是利用Intersection Observer API,性能优于滚动事件监听:
设置观察哨元素
<div v-for="item in items" :key="item.id">{{ item.content }}</div>
<div ref="sentinel"></div>
创建观察器
mounted() {
const observer = new IntersectionObserver(([entry]) => {
if (entry.isIntersecting) {
this.loadMore()
}
})
observer.observe(this.$refs.sentinel)
}
结合axios实现数据加载
分页加载逻辑
data() {
return {
page: 1,
isLoading: false,
hasMore: true
}
},
methods: {
async loadMore() {
if (this.isLoading || !this.hasMore) return
this.isLoading = true
try {
const res = await axios.get('/api/data', { params: { page: this.page } })
this.items.push(...res.data)
this.hasMore = res.data.length > 0
this.page++
} finally {
this.isLoading = false
}
}
}
优化建议
添加防抖处理避免频繁触发:
import { debounce } from 'lodash'
methods: {
handleScroll: debounce(function(e) {
// 滚动逻辑
}, 100)
}
显示加载状态:
<div v-if="isLoading" class="loading">加载中...</div>
<div v-if="!hasMore" class="no-more">没有更多数据了</div>
注意事项
- 确保滚动容器有固定高度和
overflow-y: scroll样式 - 移动端可能需要考虑
touch事件 - 大量数据渲染时建议使用虚拟滚动优化性能







