vue实现表格复选
Vue实现表格复选的步骤
基础实现
使用v-model绑定复选框和数组,通过v-for渲染表格行。
<template>
<table>
<thead>
<tr>
<th><input type="checkbox" v-model="selectAll" @change="toggleAll"></th>
<th>ID</th>
<th>Name</th>
</tr>
</thead>
<tbody>
<tr v-for="item in tableData" :key="item.id">
<td><input type="checkbox" v-model="selectedItems" :value="item.id"></td>
<td>{{ item.id }}</td>
<td>{{ item.name }}</td>
</tr>
</tbody>
</table>
</template>
<script>
export default {
data() {
return {
tableData: [
{ id: 1, name: 'Item 1' },
{ id: 2, name: 'Item 2' },
{ id: 3, name: 'Item 3' }
],
selectedItems: [],
selectAll: false
}
},
methods: {
toggleAll() {
this.selectedItems = this.selectAll ? this.tableData.map(item => item.id) : []
}
}
}
</script>
性能优化方案
对于大数据量表格,使用虚拟滚动或分页加载。
<template>
<div class="virtual-scroll" @scroll="handleScroll">
<div class="scroll-content" :style="{ height: totalHeight + 'px' }">
<div v-for="(item, index) in visibleData" :key="item.id" :style="{ transform: `translateY(${item.offset}px)` }">
<input type="checkbox" v-model="selectedItems" :value="item.id">
{{ item.name }}
</div>
</div>
</div>
</template>
高级功能实现
添加行点击选中、Shift多选等增强交互。
methods: {
handleRowClick(item, event) {
if (event.shiftKey && this.lastSelected) {
const start = this.tableData.findIndex(i => i.id === this.lastSelected)
const end = this.tableData.findIndex(i => i.id === item.id)
const range = this.tableData.slice(Math.min(start, end), Math.max(start, end) + 1)
range.forEach(row => {
if (!this.selectedItems.includes(row.id)) {
this.selectedItems.push(row.id)
}
})
} else {
const index = this.selectedItems.indexOf(item.id)
if (index === -1) {
this.selectedItems.push(item.id)
} else {
this.selectedItems.splice(index, 1)
}
}
this.lastSelected = item.id
}
}
状态管理方案
对于复杂应用,建议使用Vuex管理选中状态。
// store.js
export default new Vuex.Store({
state: {
selectedItems: []
},
mutations: {
TOGGLE_ITEM(state, itemId) {
const index = state.selectedItems.indexOf(itemId)
if (index === -1) {
state.selectedItems.push(itemId)
} else {
state.selectedItems.splice(index, 1)
}
},
CLEAR_SELECTION(state) {
state.selectedItems = []
}
}
})
样式优化技巧
添加CSS改善用户体验,如悬停效果和选中状态。
tr:hover {
background-color: #f5f5f5;
}
tr.selected {
background-color: #e3f2fd;
}
input[type="checkbox"] {
cursor: pointer;
}





