elementui表格增删改查
时间: 2023-09-20 13:09:33 浏览: 87
对vue + elementUI的表格常规增删改查优化封装
好的,您可以参考以下代码实现element-ui表格的增删改查功能:
HTML部分:
```
<el-table :data="tableData">
<el-table-column prop="name" label="姓名"></el-table-column>
<el-table-column prop="age" label="年龄"></el-table-column>
<el-table-column label="操作">
<template slot-scope="scope">
<el-button type="primary" icon="el-icon-edit" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
<el-button type="danger" icon="el-icon-delete" @click="handleDelete(scope.$index)">删除</el-button>
</template>
</el-table-column>
</el-table>
<el-dialog :visible.sync="dialogVisible">
<el-form :model="form">
<el-form-item label="姓名">
<el-input v-model="form.name" autocomplete="off"></el-input>
</el-form-item>
<el-form-item label="年龄">
<el-input v-model="form.age" autocomplete="off"></el-input>
</el-form-item>
</el-form>
<div slot="footer" class="dialog-footer">
<el-button @click="dialogVisible = false">取 消</el-button>
<el-button type="primary" @click="handleSave">确 定</el-button>
</div>
</el-dialog>
```
JavaScript部分:
```
data() {
return {
tableData: [
{ name: '张三', age: 18 },
{ name: '李四', age: 20 },
{ name: '王五', age: 22 }
],
dialogVisible: false,
form: {
name: '',
age: ''
},
editIndex: null
}
},
methods: {
handleAdd() {
this.form = {
name: '',
age: ''
};
this.dialogVisible = true;
this.editIndex = null;
},
handleEdit(index, row) {
this.form = {
name: row.name,
age: row.age
};
this.dialogVisible = true;
this.editIndex = index;
},
handleSave() {
if (this.editIndex !== null) {
this.tableData.splice(this.editIndex, 1, this.form);
} else {
this.tableData.push(this.form);
}
this.dialogVisible = false;
},
handleDelete(index) {
this.tableData.splice(index, 1);
}
}
```
利用以上代码,您就可以实现elementui表格的增删改查功能了。当点击“编辑”按钮时,会弹出dialog框,使您可以编写或修改某一项的信息。在dialog框内,您可以点击“确定”保存修改或添加新的数据项,也可以点击“取消”退出dialog框。而当点击“删除”按钮时,该数据项将会被立即删除。
阅读全文