vue实现选中单元格
Vue 实现选中单元格的方法
使用 v-bind 和 v-on 动态绑定类与事件
通过 v-bind:class 动态添加选中样式类,结合 v-on:click 处理点击事件。在数据中维护一个 selectedCell 变量存储当前选中单元格的坐标。

<template>
<table>
<tr v-for="(row, rowIndex) in grid" :key="rowIndex">
<td
v-for="(cell, colIndex) in row"
:key="colIndex"
:class="{ 'selected': isSelected(rowIndex, colIndex) }"
@click="selectCell(rowIndex, colIndex)"
>
{{ cell }}
</td>
</tr>
</table>
</template>
<script>
export default {
data() {
return {
grid: [
['A1', 'B1', 'C1'],
['A2', 'B2', 'C2']
],
selectedCell: null
}
},
methods: {
selectCell(row, col) {
this.selectedCell = { row, col };
},
isSelected(row, col) {
return this.selectedCell &&
this.selectedCell.row === row &&
this.selectedCell.col === col;
}
}
}
</script>
<style>
.selected {
background-color: #42b983;
color: white;
}
</style>
使用计算属性优化选中逻辑
通过计算属性生成一个二维数组,标记哪些单元格应被选中,减少模板中的逻辑判断。

<script>
export default {
computed: {
selectionGrid() {
return this.grid.map((row, rowIndex) =>
row.map((_, colIndex) =>
this.isSelected(rowIndex, colIndex)
)
);
}
}
}
</script>
支持多选模式
扩展功能以支持按住 Ctrl 键多选单元格,通过维护一个 selectedCells 数组来存储所有选中项。
<script>
export default {
data() {
return {
selectedCells: []
}
},
methods: {
handleCellClick(row, col, event) {
if (event.ctrlKey) {
const index = this.selectedCells.findIndex(cell =>
cell.row === row && cell.col === col
);
if (index >= 0) {
this.selectedCells.splice(index, 1);
} else {
this.selectedCells.push({ row, col });
}
} else {
this.selectedCells = [{ row, col }];
}
}
}
}
</script>
使用第三方库
对于复杂表格需求,可以集成专门的表格库如 vue-table-component 或 ag-grid-vue,它们内置了单元格选择功能。
npm install ag-grid-vue
<template>
<ag-grid-vue
:rowData="rowData"
:columnDefs="columnDefs"
rowSelection="multiple"
@cellClicked="onCellClicked"
/>
</template>
注意事项
- 性能优化:对于大型表格,避免在模板中进行复杂计算,优先使用计算属性
- 无障碍访问:为选中状态添加
aria-selected属性 - 样式隔离:使用
scoped样式防止污染全局样式表 - 移动端适配:考虑添加触摸事件支持
以上方法可根据实际需求组合或调整,核心思路是通过数据驱动视图更新,保持选中状态与数据的同步。






