vue中表格实现单选
实现 Vue 表格单选功能
在 Vue 中实现表格的单选功能,可以通过以下方法完成。假设使用的是 Element UI 或其他类似的 UI 框架,以下是具体实现方式。
使用 Element UI 的表格单选
Element UI 的表格组件内置了单选功能,可以通过 highlight-current-row 属性开启。
<template>
<el-table
:data="tableData"
highlight-current-row
@current-change="handleCurrentChange"
>
<el-table-column prop="name" label="姓名"></el-table-column>
<el-table-column prop="age" label="年龄"></el-table-column>
</el-table>
</template>
<script>
export default {
data() {
return {
tableData: [
{ name: '张三', age: 20 },
{ name: '李四', age: 22 },
{ name: '王五', age: 25 }
],
currentRow: null
};
},
methods: {
handleCurrentChange(val) {
this.currentRow = val;
}
}
};
</script>
自定义单选逻辑
如果不使用 UI 框架,可以通过自定义逻辑实现表格单选。
<template>
<table>
<thead>
<tr>
<th>姓名</th>
<th>年龄</th>
</tr>
</thead>
<tbody>
<tr
v-for="(item, index) in tableData"
:key="index"
@click="selectRow(index)"
:class="{ selected: selectedIndex === index }"
>
<td>{{ item.name }}</td>
<td>{{ item.age }}</td>
</tr>
</tbody>
</table>
</template>
<script>
export default {
data() {
return {
tableData: [
{ name: '张三', age: 20 },
{ name: '李四', age: 22 },
{ name: '王五', age: 25 }
],
selectedIndex: null
};
},
methods: {
selectRow(index) {
this.selectedIndex = index;
}
}
};
</script>
<style>
.selected {
background-color: #f0f0f0;
}
</style>
使用 v-model 绑定选中项
通过 v-model 绑定选中项,可以更方便地管理选中状态。
<template>
<el-table
:data="tableData"
highlight-current-row
@current-change="handleCurrentChange"
:current-row-key="currentRowKey"
>
<el-table-column prop="name" label="姓名"></el-table-column>
<el-table-column prop="age" label="年龄"></el-table-column>
</el-table>
</template>
<script>
export default {
data() {
return {
tableData: [
{ id: 1, name: '张三', age: 20 },
{ id: 2, name: '李四', age: 22 },
{ id: 3, name: '王五', age: 25 }
],
currentRowKey: null
};
},
methods: {
handleCurrentChange(val) {
this.currentRowKey = val ? val.id : null;
}
}
};
</script>
动态切换选中行
如果需要动态切换选中行,可以通过调用表格的 setCurrentRow 方法实现。
<template>
<el-table
ref="singleTable"
:data="tableData"
highlight-current-row
@current-change="handleCurrentChange"
>
<el-table-column prop="name" label="姓名"></el-table-column>
<el-table-column prop="age" label="年龄"></el-table-column>
</el-table>
<el-button @click="setCurrent">选中第二行</el-button>
</template>
<script>
export default {
data() {
return {
tableData: [
{ name: '张三', age: 20 },
{ name: '李四', age: 22 },
{ name: '王五', age: 25 }
]
};
},
methods: {
handleCurrentChange(val) {
this.currentRow = val;
},
setCurrent() {
this.$refs.singleTable.setCurrentRow(this.tableData[1]);
}
}
};
</script>
以上方法可以根据具体需求选择使用,灵活实现表格的单选功能。







