效果图:
main.js:
<template>
<div>
<div class="table">
<table border="1" cellspacing="0">
<thead>
<tr>
<th>
<el-checkbox
:value="isAllChecked()"
@change="setAllSelect()"
></el-checkbox>
</th>
<th>序号</th>
<th>名称</th>
<th>所占比例</th>
</tr>
</thead>
<tbody>
<tr v-for="(item, index) in items" :key="index">
<td>
<el-checkbox
:value="isChecked(item)"
@change="setSelect(item)"
></el-checkbox>
</td>
<td>{{ index + 1 }}</td>
<td v-text="item.name"></td>
<td v-text="item.row"></td>
</tr>
</tbody>
</table>
</div>
<pre class="">选中的数据:{{selectedItem}}</pre>
</div>
</template>
<script>
import selectTableData from "../../service/selectTableData.js";
export default {
mixins: [selectTableData],
data() {
return {
items: [
{ id: 1, name: "数据1", row: "3" },
{ id: 2, name: "数据2", row: "3" },
{ id: 3, name: "数据3", row: "3" },
{ id: 4, name: "数据4", row: "3" },
{ id: 5, name: "数据5", row: "3" },
{ id: 6, name: "数据6", row: "3" },
],
selectedItem: [],
};
},
methods:{
// 数组里面的字符串拼接
spliceStr(data,id,str){
return data.map(item=>item[id]).join(str)
}
}
};
</script>
<style lang="less" scoped>
.table {
width: 100%;
table {
width: 100%;
border: 1px solid #ccc;
tr {
td,
th {
border: 1px solid #ccc;
border-width: 0px 1px 1px 0px;
width: auto;
line-height: 40px;
text-align: center;
}
th {
background: #f7f8fa;
}
}
}
}
</style>
selectTableData.js
export default {
name: 'selectTableData',
data() {
return {
tableUID: "id",
items: [], // 列表数据
selectedItem: [], // 选中列表数据
};
},
methods: {
// 判断是否全部选中
isAllChecked() {
return (this.items.length == this.selectedItem.length && this.selectedItem.length > 0) ? true : false
},
// 设置全部选中
setAllSelect() {
this.isAllChecked() ? this.selectedItem = [] : this.selectedItem = [...this.items]
},
// 设置单选
setSelect(_item) {
if (this.isChecked(_item)) {
// 若是有改数据,则删除该数据,否则添加该数据
this.selectedItem.splice( this.selectedItem.findIndex( (item) => item[this.tableUID] ==_item[this.tableUID] ), 1 );
} else {
this.selectedItem.push(_item);
}
},
// 判断是否选中
isChecked(item) {
const flag = this.selectedItem.some((_item) => {
return _item[this.tableUID] === item[this.tableUID];
});
return flag;
},
},
};