element-- el-table表头的全选按钮后加上“全选“
时间: 2023-11-30 19:02:43 浏览: 130
可以通过以下步骤在 el-table 表头的全选按钮后加上“全选”:
1. 在 el-table 组件中添加一个 slot,用于自定义表头内容:
```html
<el-table :data="tableData" :row-key="row => row.id">
<el-table-column type="selection" width="55">
<template slot="header">
<el-checkbox v-model="isAllSelected" @change="selectAll">{{selectAllText}}</el-checkbox>
</template>
</el-table-column>
<el-table-column prop="name" label="Name"></el-table-column>
<el-table-column prop="age" label="Age"></el-table-column>
</el-table>
```
2. 在 Vue 实例中添加以下代码:
```javascript
data() {
return {
isAllSelected: false,
selectAllText: '全选',
tableData: [
{ id: 1, name: 'John', age: 20 },
{ id: 2, name: 'Jane', age: 25 },
{ id: 3, name: 'Bob', age: 30 }
]
}
},
methods: {
selectAll() {
const isSelected = this.isAllSelected
this.tableData.forEach(row => {
row.$isSelected = isSelected
})
}
},
watch: {
tableData: {
handler() {
const isAllSelected = this.tableData.every(row => row.$isSelected)
this.isAllSelected = isAllSelected
},
deep: true
}
}
```
3. 在 Vue 实例的 template 中修改 selectAllText 的值:
```html
<template>
<div>
<el-table :data="tableData" :row-key="row => row.id">
<el-table-column type="selection" width="55">
<template slot="header">
<el-checkbox v-model="isAllSelected" @change="selectAll">{{selectAllText}}</el-checkbox>
</template>
</el-table-column>
<el-table-column prop="name" label="Name"></el-table-column>
<el-table-column prop="age" label="Age"></el-table-column>
</el-table>
</div>
</template>
<script>
export default {
data() {
return {
isAllSelected: false,
selectAllText: '全选',
tableData: [
{ id: 1, name: 'John', age: 20 },
{ id: 2, name: 'Jane', age: 25 },
{ id: 3, name: 'Bob', age: 30 }
]
}
},
methods: {
selectAll() {
const isSelected = this.isAllSelected
this.tableData.forEach(row => {
row.$isSelected = isSelected
})
}
},
watch: {
tableData: {
handler() {
const isAllSelected = this.tableData.every(row => row.$isSelected)
this.isAllSelected = isAllSelected
},
deep: true
}
}
}
</script>
```
这样就可以在 el-table 表头的全选按钮后添加“全选”了。
阅读全文