模仿el-table实现多选
时间: 2023-10-14 15:26:38 浏览: 164
为了实现多选功能,我们需要在数据源中添加一个属性来记录选中状态,然后在表格中添加一个复选框列,以及一个全选复选框。当用户点击复选框时,我们需要更新数据源中对应的选中状态。
下面是一个简单的示例代码:
```html
<template>
<div>
<el-table :data="tableData" style="width: 100%">
<el-table-column type="selection" width="55"></el-table-column>
<el-table-column prop="name" label="姓名"></el-table-column>
<el-table-column prop="age" label="年龄"></el-table-column>
<el-table-column prop="address" label="地址"></el-table-column>
</el-table>
</div>
</template>
<script>
export default {
data() {
return {
tableData: [
{ name: '张三', age: 18, address: '北京', selected: false },
{ name: '李四', age: 20, address: '上海', selected: false },
{ name: '王五', age: 22, address: '广州', selected: false },
{ name: '赵六', age: 24, address: '深圳', selected: false }
]
}
},
computed: {
// 计算选中的行数
selectedCount() {
return this.tableData.filter(row => row.selected).length
},
// 是否全选
isAllSelected() {
return this.selectedCount === this.tableData.length
}
},
methods: {
// 全选/取消全选
toggleSelectAll(checked) {
this.tableData.forEach(row => {
row.selected = checked
})
},
// 切换选中状态
toggleSelect(row) {
row.selected = !row.selected
}
}
}
</script>
```
在这个示例中,我们添加了一个`selected`属性来记录每一行的选中状态。`computed`中的`selectedCount`计算选中的行数,`isAllSelected`判断是否全选。
在模板中,我们在表格中添加了一个类型为`selection`的列,用来显示复选框。同时,我们添加了一个全选复选框,绑定`toggleSelectAll`方法。当用户点击复选框时,我们调用`toggleSelect`方法来更新数据源中对应的选中状态。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)