vue表格实现单选框
Vue 表格实现单选框的方法
在 Vue 中实现表格单选框功能,可以通过结合 el-table(Element UI)或原生表格与 Vue 的数据绑定特性完成。以下是几种常见实现方式:
使用 Element UI 的 el-table 组件
Element UI 提供了内置的单选框支持,可直接在表格中启用。
<template>
<el-table
:data="tableData"
@selection-change="handleSelectionChange"
style="width: 100%">
<el-table-column
type="selection"
width="55">
</el-table-column>
<el-table-column
prop="name"
label="姓名">
</el-table-column>
</el-table>
</template>
<script>
export default {
data() {
return {
tableData: [
{ name: '张三' },
{ name: '李四' }
],
selectedRow: null
};
},
methods: {
handleSelectionChange(val) {
this.selectedRow = val.length > 0 ? val[0] : null;
}
}
};
</script>
关键点:
- 设置
type="selection"启用复选框列。 - 通过
@selection-change监听选中变化,仅保留最后一项实现单选效果。
自定义单选框(原生或第三方库)
若需完全自定义单选框样式或逻辑,可通过手动绑定实现:
<template>
<table>
<tr v-for="(item, index) in tableData" :key="index">
<td>
<input
type="radio"
:value="item.id"
v-model="selectedId"
@change="handleRadioChange(item)">
</td>
<td>{{ item.name }}</td>
</tr>
</table>
</template>
<script>
export default {
data() {
return {
tableData: [
{ id: 1, name: '张三' },
{ id: 2, name: '李四' }
],
selectedId: null
};
},
methods: {
handleRadioChange(item) {
console.log('选中项:', item);
}
}
};
</script>
关键点:
- 使用
v-model绑定单选值(如selectedId)。 - 通过
@change事件触发自定义逻辑。
使用 Vue 计算属性优化
若需动态禁用某些选项,可结合计算属性:
computed: {
disabledItems() {
return this.tableData.map(item => item.id === 2); // 禁用ID为2的项
}
}
在模板中绑定 :disabled 属性:
<input
type="radio"
:disabled="disabledItems[index]">
注意事项
- 数据一致性:确保
v-model绑定的值与选项的value属性匹配。 - 性能:大数据量时建议使用虚拟滚动(如
el-table的虚拟滚动功能)。 - 样式:自定义单选框时可能需要隐藏原生输入框并用 CSS 美化。
通过以上方法,可灵活实现 Vue 表格中的单选功能,适应不同场景需求。







