以下是純Vue實現的表格多選方案(不依賴UI庫),支持跨頁選擇和回顯功能:
<template><div class="custom-table"><!-- 表格主體 --><table><thead><tr><th><input type="checkbox" :checked="isAllChecked"@change="toggleAllSelection"></th><th>ID</th><th>Name</th><th>Age</th></tr></thead><tbody><tr v-for="item in currentPageData" :key="item.id"><td><inputtype="checkbox":checked="isSelected(item.id)"@change="toggleSelection(item)"></td><td>{{ item.id }}</td><td>{{ item.name }}</td><td>{{ item.age }}</td></tr></tbody></table><!-- 分頁控件 --><div class="pagination"><button v-for="page in totalPages" :key="page":class="{ active: currentPage === page }"@click="currentPage = page">{{ page }}</button></div><!-- 已選展示 --><div class="selected-info">已選ID: {{ selectedIds.join(', ') }}</div></div>
</template><script>
export default {data() {return {// 原始數據allData: [],// 分頁相關currentPage: 1,pageSize: 5,// 選中數據selectedItems: new Map(), // 使用Map存儲保證順序}},computed: {// 當前頁數據currentPageData() {const start = (this.currentPage - 1) * this.pageSizeconst end = start + this.pageSizereturn this.allData.slice(start, end)},// 總頁數totalPages() {return Math.ceil(this.allData.length / this.pageSize)},// 當前頁是否全選isAllChecked() {return this.currentPageData.every(item => this.selectedItems.has(item.id))},// 已選ID數組selectedIds() {return Array.from(this.selectedItems.keys())}},created() {// 生成模擬數據this.generateMockData(23)// 模擬回顯數據(實際從API獲取)this.$nextTick(() => {this.setInitialSelection([2, 5, 9]) // 回顯ID為2、5、9的數據})},methods: {// 生成模擬數據generateMockData(count) {for(let i = 1; i <= count; i++) {this.allData.push({id: i,name: `User ${i}`,age: 20 + (i % 10)})}},// 設置初始選中(回顯)setInitialSelection(ids) {ids.forEach(id => {const item = this.allData.find(d => d.id === id)if(item) this.selectedItems.set(id, item)})},// 切換單個選擇toggleSelection(item) {if(this.selectedItems.has(item.id)) {this.selectedItems.delete(item.id)} else {this.selectedItems.set(item.id, item)}},// 切換全選toggleAllSelection(e) {const checked = e.target.checkedthis.currentPageData.forEach(item => {if(checked) {this.selectedItems.set(item.id, item)} else {this.selectedItems.delete(item.id)}})},// 檢查是否選中isSelected(id) {return this.selectedItems.has(id)}}
}
</script><style scoped>
.custom-table {max-width: 800px;margin: 20px auto;font-family: Arial, sans-serif;
}table {width: 100%;border-collapse: collapse;margin-bottom: 20px;
}th, td {border: 1px solid #ddd;padding: 12px;text-align: left;
}th {background-color: #f5f5f5;
}tr:hover {background-color: #f9f9f9;
}.pagination {display: flex;gap: 8px;margin-bottom: 20px;
}.pagination button {padding: 6px 12px;border: 1px solid #ddd;background: white;cursor: pointer;border-radius: 4px;
}.pagination button.active {background: #409eff;color: white;border-color: #409eff;
}.selected-info {padding: 12px;background: #f5f5f5;border-radius: 4px;
}
</style>
核心實現邏輯:
-
數據結構設計:
allData
:存儲全部數據(模擬數據)selectedItems
:使用Map存儲選中項,方便快速查找currentPageData
:計算屬性獲取當前頁數據
-
跨頁選擇實現:
- 使用Map存儲選中項,不受分頁影響
- 切換頁面時自動保留選中狀態
- 通過
isSelected
方法檢查當前行是否選中
-
回顯功能:
- 提供
setInitialSelection
方法初始化選中項 - 支持傳入ID數組自動匹配數據項
- 提供
-
全選功能:
- 當前頁全選/取消全選
- 自動同步到全局選中狀態
- 智能顯示全選復選框狀態
-
性能優化:
- 使用Map數據結構提升查找效率
- 計算屬性緩存計算結果
- 虛擬滾動友好(可擴展)
功能擴展建議:
-
分頁優化:
// 在methods中添加 goToPage(page) {if(page < 1 || page > this.totalPages) returnthis.currentPage = page }// 在模板中添加 <button @click="goToPage(currentPage - 1)">上一頁</button> <button @click="goToPage(currentPage + 1)">下一頁</button>
-
多選操作增強:
// 清空選擇 clearSelection() {this.selectedItems.clear() }// 批量刪除 deleteSelected() {this.allData = this.allData.filter(item => !this.selectedItems.has(item.id)this.clearSelection() }
-
數據持久化:
// 本地存儲示例 watch: {selectedItems: {handler(newVal) {localStorage.setItem('selectedItems', JSON.stringify([...newVal]))},deep: true} }
-
性能增強(大數據量):
// 使用虛擬滾動 // 安裝vue-virtual-scroller import { RecycleScroller } from 'vue-virtual-scroller'// 替換tbody部分 <RecycleScrollerclass="scroller":items="currentPageData":item-size="48"key-field="id" ><template #default="{ item }"><tr><!-- 原有td內容 --></tr></template> </RecycleScroller>
使用說明:
- 通過
setInitialSelection
方法初始化回顯數據 - 獲取選中數據:
Array.from(this.selectedItems.values())
- 修改
pageSize
可調整每頁顯示數量 - 樣式可根據需求自定義修改
這個實現方案具有以下特點:
- 零依賴,純Vue實現
- 完整的分頁選擇邏輯
- 高性能的選中狀態管理
- 靈活的回顯機制
- 易于擴展的自定義樣式
- 支持大數據量的虛擬滾動(需額外配置)