vue实现表格取消选择
Vue 实现表格取消选择的方法
使用 v-model 和 computed 属性
在表格中绑定选中状态,通过计算属性管理选中项。取消选择时,直接操作绑定的数组。

<template>
<table>
<tr v-for="item in items" :key="item.id">
<td>
<input
type="checkbox"
v-model="selectedItems"
:value="item.id"
>
</td>
<td>{{ item.name }}</td>
</tr>
<button @click="clearSelection">取消选择</button>
</table>
</template>
<script>
export default {
data() {
return {
items: [
{ id: 1, name: 'Item 1' },
{ id: 2, name: 'Item 2' }
],
selectedItems: []
}
},
methods: {
clearSelection() {
this.selectedItems = []
}
}
}
</script>
使用 ref 和 DOM 操作
通过 ref 获取所有复选框元素,手动取消选中状态。

<template>
<table>
<tr v-for="item in items" :key="item.id">
<td>
<input
type="checkbox"
:ref="`checkbox-${item.id}`"
@change="handleSelect(item.id)"
>
</td>
<td>{{ item.name }}</td>
</tr>
<button @click="clearSelection">取消选择</button>
</table>
</template>
<script>
export default {
data() {
return {
items: [
{ id: 1, name: 'Item 1' },
{ id: 2, name: 'Item 2' }
],
selectedItems: []
}
},
methods: {
handleSelect(id) {
const index = this.selectedItems.indexOf(id)
if (index === -1) {
this.selectedItems.push(id)
} else {
this.selectedItems.splice(index, 1)
}
},
clearSelection() {
this.selectedItems = []
this.items.forEach(item => {
this.$refs[`checkbox-${item.id}`][0].checked = false
})
}
}
}
</script>
使用事件代理
在表格外层元素上监听点击事件,通过事件委托处理取消选择逻辑。
<template>
<div @click="handleTableClick">
<table ref="table">
<tr v-for="item in items" :key="item.id">
<td>
<input
type="checkbox"
:data-id="item.id"
:checked="selectedItems.includes(item.id)"
>
</td>
<td>{{ item.name }}</td>
</tr>
</table>
<button @click="clearSelection">取消选择</button>
</div>
</template>
<script>
export default {
data() {
return {
items: [
{ id: 1, name: 'Item 1' },
{ id: 2, name: 'Item 2' }
],
selectedItems: []
}
},
methods: {
handleTableClick(e) {
if (e.target.type === 'checkbox') {
const id = Number(e.target.dataset.id)
this.toggleSelection(id)
}
},
toggleSelection(id) {
const index = this.selectedItems.indexOf(id)
if (index === -1) {
this.selectedItems.push(id)
} else {
this.selectedItems.splice(index, 1)
}
},
clearSelection() {
this.selectedItems = []
const checkboxes = this.$refs.table.querySelectorAll('input[type="checkbox"]')
checkboxes.forEach(checkbox => {
checkbox.checked = false
})
}
}
}
</script>
使用第三方表格组件
如果使用 Element UI 等组件库,可以利用其内置方法实现取消选择。
<template>
<el-table
ref="multipleTable"
:data="items"
@selection-change="handleSelectionChange"
>
<el-table-column type="selection" width="55"></el-table-column>
<el-table-column prop="name" label="Name"></el-table-column>
</el-table>
<el-button @click="clearSelection">取消选择</el-button>
</template>
<script>
export default {
data() {
return {
items: [
{ id: 1, name: 'Item 1' },
{ id: 2, name: 'Item 2' }
],
selectedItems: []
}
},
methods: {
handleSelectionChange(val) {
this.selectedItems = val
},
clearSelection() {
this.$refs.multipleTable.clearSelection()
}
}
}
</script>






