功能目標:
CardList.vue
中支持分頁,每頁顯示指定數量的卡片。- 添加“加載中”動畫。
- 支持懶加載:滾動到底部自動加載下一頁。
- 點擊卡片的事件邏輯由
Card.vue
內部發出,并由CardList
向上傳遞。
主頁面文件 Home.vue
<template><div><h1>Card List 示例</h1><CardList :dataList="cards" @card-click="handleCardClick" /></div>
</template><script>
import CardList from './components/CardList.vue'export default {name: 'Home',components: {CardList},data() {return {// 假設這是全部數據(實際應用中可從API分頁加載)cards: Array.from({ length: 50 }, (_, i) => ({id: i + 1,title: `Card #${i + 1}`,description: `This is card number ${i + 1}.`}))}},methods: {handleCardClick(card) {alert(`你點擊了: ${card.title}`)}}
}
</script>
CardList.vue
(分頁 + 懶加載 + 加載動畫)
<template><div class="card-list"><Cardv-for="item in paginatedList":key="item.id":cardData="item"@card-click="handleCardClick"/><div v-if="loading" class="loading">加載中...</div></div>
</template><script>
import Card from './Card.vue'export default {name: 'CardList',components: { Card },props: {dataList: {type: Array,required: true}},data() {return {pageSize: 10,currentPage: 1,loading: false}},computed: {paginatedList() {return this.dataList.slice(0, this.currentPage * this.pageSize)}},mounted() {window.addEventListener('scroll', this.onScroll)},beforeDestroy() {window.removeEventListener('scroll', this.onScroll)},methods: {handleCardClick(card) {this.$emit('card-click', card)},onScroll() {const scrollBottom = window.innerHeight + window.scrollY >= document.body.offsetHeight - 10if (scrollBottom && !this.loading && this.canLoadMore) {this.loadNextPage()}},loadNextPage() {this.loading = truesetTimeout(() => {this.currentPage++this.loading = false}, 1000) // 模擬加載延遲}},computed: {canLoadMore() {return this.paginatedList.length < this.dataList.length}}
}
</script><style scoped>
.card-list {display: flex;flex-wrap: wrap;gap: 16px;
}.loading {width: 100%;text-align: center;padding: 16px;color: #999;font-style: italic;
}
</style>
Card.vue
(點擊內部觸發)
<template><div class="card" @click="handleClick"><h3>{{ cardData.title }}</h3><p>{{ cardData.description }}</p></div>
</template><script>
export default {name: 'Card',props: {cardData: {type: Object,required: true}},methods: {handleClick() {this.$emit('card-click', this.cardData)}}
}
</script><style scoped>
.card {border: 1px solid #ccc;padding: 16px;border-radius: 8px;cursor: pointer;width: 200px;transition: box-shadow 0.2s;
}
.card:hover {box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
}
</style>
總結:
這是一個基于 Vue 2 開發的可復用卡片列表組件,支持以下功能:
- 分頁加載:初始顯示部分數據,滾動到底部自動加載更多;
- 懶加載機制:通過監聽頁面滾動事件實現無限加載;
- 點擊交互:每個卡片可點擊,事件由卡片內部觸發并向上傳遞;
- 加載狀態顯示:加載新數據時展示“加載中…”提示;