(1)首先创建一个文件名为:InfiniteScroll.vue
<template>
<div ref="scrollContainer" class="infinite-scroll-container">
<slot></slot>
<div v-if="loading" class="loading-spinner">加载中...</div>
</div>
</template>
<script setup>
import {
ref,
onMounted,
onUnmounted,
defineProps
} from 'vue';
const props = defineProps({
loadMore: {
type: Function,
required: true
},
loading: {
type: Boolean,
default: false
}
});
const scrollContainer = ref(null);
const handleScroll = () => {
if (!scrollContainer.value) return;
const container = scrollContainer.value;
const containerHeight = container.clientHeight;
const scrollTop = container.scrollTop;
const contentHeight = container.scrollHeight;
if (scrollTop + containerHeight >= contentHeight - 10) {
//触发逻辑
if (!props.loading) {
props.loadMore();
}
}
};
onMounted(() => {
if (scrollContainer.value) {
scrollContainer.value.addEventListener('scroll', handleScroll);
}
});
onUnmounted(() => {
if (scrollContainer.value) {
scrollContainer.value.removeEventListener('scroll', handleScroll);
}
});
</script>
<style scoped>
.infinite-scroll-container {
overflow-y: auto;
position: relative;
}
.loading-spinner {
text-align: center;
padding: 10px;
}
</style>
(2)如何使用
<template>
<InfiniteScroll :loadMore="loadMoreData" :loading="loading">
<!-- 列表内容 -->
<div v-if="isEnd" class="end-message">已经到底了</div>
</InfiniteScroll>
</template>
<style scoped>
.end-message {
text-align: center;
padding: 10px;
color: #888;
}
</style>
示例:
<InfiniteScroll :loadMore="loadMoreData" class="shellwantbuy-center" v-if="buylstData.length>0">
<div class="shellwantbuy-center-item" v-for="(item,index) in buylstData" :key="item">
内容展示
</div>
<div v-if="isEnd" class="end-message">已经到底了</div>
<div v-if="loading" class="loading-spinner">加载中...</div>
</InfiniteScroll>
<script setup>
import {
Tradewanttobuypull,
Tradewanttobuyuserlst
} from '@/api/modules/secondarymMarket'
import InfiniteScroll from '@/components/InfiniteScroll.vue'
import {
onMounted,
ref,
watch
} from 'vue'
import empyt from '@/components/EmptyState.vue'
const buylstData = ref([])
const token = uni.getStorageSync('token')
const page = ref(1);
const pageSize = 10;
const loading = ref(false);
const last_page = ref()
const isEnd = ref(false);
const loadMoreData = async () => {
if (loading.value) return;
loading.value = true;
try {
const data = await Tradewanttobuyuserlst({
page_size: pageSize,
page: page.value,
type: '1',
token,
});
const buydata = data;
last_page.value = buydata.data.last_page
console.log(page.value,last_page.value)
if (page.value <= last_page.value) {
buylstData.value.push(...buydata.data.data);
page.value++;
} else {
isEnd.value = true;
}
} catch (error) {
console.error('Failed to load data:', error);
} finally {
loading.value = false;
}
};
onMounted(() => {
loadMoreData()
})
</script>