演示地址:https://codepen.io/abu3389/pen/rNemWvm
思路:el-radio 只作为展示容器,我们利用@row-click 的参数 row 就能拿到表格当前点击行的数据
<el-table @row-click="handleRowClick" :data="tableList" border fit highlight-current-row>
<el-table-column label="选择" width="50" fixed="left" center>
<template slot-scope="scope">
<el-radio v-model="nowIndex" :label="scope.row.radioId"
> </el-radio>
</template>
</el-table-column>
<el-table-column prop="name" label="物品名称" align="center"></el-table-column>
<el-table-column prop="price" label="物品价格" align="center"></el-table-column>
</el-table>
data() {
return {
// 数据列表
tableList: [
{
name: "物品1",
price: "100"
},
{
name: "物品2",
price: "88"
},
{
name: "物品3",
price: "66"
},
],
// 当前选择的单项框值
nowIndex: "",
//选择的信息
nowRow: "",
};
},
初始化给每个数据项添加绑定数值radioId :
created() {
this.tableList = this.tableList.map((item, index) => {
item.radioId = index;
return item;
});
},
这时候就可以利用行点击回调的数据row轻而易举的切换单选的样式了,根本不用网上说的那么麻烦
//行点击
handleRowClick(row, column, event) {
this.nowIndex = row.radioId;
this.nowRow = row;
console.log("当前单选框的值:", this.nowIndex)
console.log("当前行的数据:", this.nowRow)
},
再调整下el-radio的样式:
<style lang="scss" scoped>
//隐藏el-radio的label
.el-radio__label {
display: none;
}
//让radio在单元格中居中,center不生效
.el-table__row .el-table_1_column_1 .cell {
text-align: center;
}
</style>