vue表格实现加载更多
实现 Vue 表格加载更多的几种方法
滚动加载(无限滚动)
通过监听滚动事件,当滚动到底部时加载更多数据。适用于长列表或表格。
<template>
<div class="table-container" @scroll="handleScroll">
<table>
<!-- 表格内容 -->
</table>
<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
try {
const newItems = await fetchData(this.page)
if (newItems.length) {
this.items = [...this.items, ...newItems]
this.page++
} else {
this.hasMore = false
}
} finally {
this.loading = false
}
},
handleScroll(e) {
const { scrollTop, clientHeight, scrollHeight } = e.target
if (scrollHeight - (scrollTop + clientHeight) < 50) {
this.loadMore()
}
}
}
}
</script>
分页加载按钮
添加"加载更多"按钮,点击后加载下一页数据。
<template>
<div>
<table>
<!-- 表格内容 -->
</table>
<button
v-if="hasMore"
@click="loadMore"
:disabled="loading"
>
{{ loading ? '加载中...' : '加载更多' }}
</button>
</div>
</template>
使用 Intersection Observer API
更现代的无限滚动实现方式,性能优于传统滚动事件监听。
methods: {
initObserver() {
const observer = new IntersectionObserver((entries) => {
if (entries[0].isIntersecting) {
this.loadMore()
}
})
observer.observe(this.$refs.observerElement)
}
}
使用第三方库
可以考虑使用现成的Vue无限滚动库如vue-infinite-loading:
import InfiniteLoading from 'vue-infinite-loading'
export default {
components: { InfiniteLoading },
methods: {
async infiniteHandler($state) {
try {
const newItems = await fetchData(this.page)
if (newItems.length) {
this.items.push(...newItems)
this.page++
$state.loaded()
} else {
$state.complete()
}
} catch (e) {
$state.error()
}
}
}
}
性能优化建议
对于大数据量表格,应配合虚拟滚动技术使用,避免DOM节点过多导致性能问题。可考虑使用vue-virtual-scroller等库实现虚拟滚动。







