vue用element-ui的表格,在表格中实现批量编辑
时间: 2024-05-14 13:12:03 浏览: 157
vue+element-ui实现表格编辑的三种实现方式
要实现表格中的批量编辑,可以在表格中添加一个“编辑”按钮或者复选框,当用户勾选了多个行或者点击了“编辑”按钮时,可以打开一个弹窗或者对话框,让用户同时编辑多个行的字段值。
以下是一个简单的示例:
1. 在表格中添加一个复选框列:
```
<template>
<el-table :data="tableData" style="width: 100%">
<el-table-column type="selection"></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="gender" label="性别"></el-table-column>
</el-table>
</template>
<script>
export default {
data() {
return {
tableData: [
{ name: '张三', age: 20, gender: '男' },
{ name: '李四', age: 25, gender: '女' },
{ name: '王五', age: 30, gender: '男' },
{ name: '赵六', age: 35, gender: '女' }
]
}
}
}
</script>
```
2. 在表格上方添加一个“编辑”按钮和一个勾选数量的显示:
```
<template>
<div>
<el-button type="primary" @click="handleEdit">编辑</el-button>
<span v-if="selectedRows.length">已选{{selectedRows.length}}行</span>
<el-table :data="tableData" style="width: 100%">
<!-- 省略表格列定义 -->
</el-table>
</div>
</template>
<script>
export default {
data() {
return {
tableData: [
{ name: '张三', age: 20, gender: '男' },
{ name: '李四', age: 25, gender: '女' },
{ name: '王五', age: 30, gender: '男' },
{ name: '赵六', age: 35, gender: '女' }
],
selectedRows: []
}
},
methods: {
handleEdit() {
// 弹出编辑对话框或者弹窗
}
},
watch: {
// 监听勾选的行
'$refs.table.selection': function(val) {
this.selectedRows = val
}
}
}
</script>
```
3. 在“编辑”对话框或者弹窗中显示被勾选行的字段值,并允许用户同时修改多个行的字段值:
```
<template>
<el-dialog title="批量编辑" :visible.sync="dialogVisible">
<el-form :model="formData">
<el-form-item label="年龄">
<el-input v-model="formData.age"></el-input>
</el-form-item>
<el-form-item label="性别">
<el-radio v-model="formData.gender" label="男">男</el-radio>
<el-radio v-model="formData.gender" label="女">女</el-radio>
</el-form-item>
</el-form>
<div slot="footer">
<el-button @click="dialogVisible = false">取消</el-button>
<el-button type="primary" @click="handleSave">保存</el-button>
</div>
</el-dialog>
</template>
<script>
export default {
data() {
return {
dialogVisible: false,
formData: {
age: '',
gender: ''
}
}
},
methods: {
handleSave() {
for (let row of this.selectedRows) {
row.age = this.formData.age
row.gender = this.formData.gender
}
this.dialogVisible = false
}
},
watch: {
selectedRows: function(val) {
if (val.length) {
this.formData.age = val[0].age
this.formData.gender = val[0].gender
for (let row of val) {
if (row.age !== val[0].age) {
this.formData.age = ''
}
if (row.gender !== val[0].gender) {
this.formData.gender = ''
}
}
this.dialogVisible = true
}
}
}
}
</script>
```
阅读全文