vue实现更多加载
Vue实现更多加载功能
在Vue中实现更多加载(无限滚动或分页加载)功能,可以通过监听滚动事件或使用Intersection Observer API来实现。以下是两种常见的方法:
监听滚动事件
通过监听滚动事件,判断是否滚动到底部,触发加载更多数据。
<template>
<div class="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: [],
loading: false,
page: 1,
};
},
mounted() {
this.fetchData();
},
methods: {
handleScroll(event) {
const container = event.target;
const scrollBottom = container.scrollHeight - container.scrollTop - container.clientHeight;
if (scrollBottom < 50 && !this.loading) {
this.fetchData();
}
},
fetchData() {
this.loading = true;
// 模拟API调用
setTimeout(() => {
const newItems = Array.from({ length: 10 }, (_, i) => ({
id: this.items.length + i,
content: `Item ${this.items.length + i}`,
}));
this.items = [...this.items, ...newItems];
this.page++;
this.loading = false;
}, 1000);
},
},
};
</script>
<style>
.container {
height: 300px;
overflow-y: auto;
border: 1px solid #ccc;
}
</style>
使用Intersection Observer API
Intersection Observer API更高效,适合现代浏览器。
<template>
<div class="container">
<div v-for="item in items" :key="item.id">
{{ item.content }}
</div>
<div ref="loader" v-if="loading">加载中...</div>
</div>
</template>
<script>
export default {
data() {
return {
items: [],
loading: false,
page: 1,
observer: null,
};
},
mounted() {
this.fetchData();
this.observer = new IntersectionObserver((entries) => {
if (entries[0].isIntersecting && !this.loading) {
this.fetchData();
}
});
this.observer.observe(this.$refs.loader);
},
beforeDestroy() {
this.observer.disconnect();
},
methods: {
fetchData() {
this.loading = true;
setTimeout(() => {
const newItems = Array.from({ length: 10 }, (_, i) => ({
id: this.items.length + i,
content: `Item ${this.items.length + i}`,
}));
this.items = [...this.items, ...newItems];
this.page++;
this.loading = false;
}, 1000);
},
},
};
</script>
使用第三方库
可以使用第三方库如vue-infinite-loading简化实现。
安装:
npm install vue-infinite-loading
使用:
<template>
<div>
<div v-for="item in items" :key="item.id">
{{ item.content }}
</div>
<InfiniteLoading @infinite="fetchData" />
</div>
</template>
<script>
import InfiniteLoading from 'vue-infinite-loading';
export default {
components: {
InfiniteLoading,
},
data() {
return {
items: [],
page: 1,
};
},
methods: {
fetchData($state) {
setTimeout(() => {
const newItems = Array.from({ length: 10 }, (_, i) => ({
id: this.items.length + i,
content: `Item ${this.items.length + i}`,
}));
this.items = [...this.items, ...newItems];
this.page++;
$state.loaded();
if (this.page > 5) {
$state.complete();
}
}, 1000);
},
},
};
</script>
注意事项
- 确保在组件销毁时取消事件监听或断开Observer,避免内存泄漏。
- 在加载数据时添加锁机制,防止重复请求。
- 根据实际需求调整触发加载的阈值(如距离底部的距离)。







