vue3 +element+ts表格编辑保存取消按钮切换
时间: 2023-08-01 08:11:11 浏览: 158
在Vue3中,可以使用`<el-dialog>`组件来实现表格的编辑功能。同时,我们可以通过响应式数据来保存表格的数据,使用TypeScript来更好地管理代码和类型。
以下是一个示例代码,实现了表格的增删改查功能:
```typescript
<template>
<div>
<el-button type="primary" @click="addRow">添加</el-button>
<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 #default="{ row }">
<el-button type="primary" @click="editRow(row)">编辑</el-button>
<el-button type="danger" @click="deleteRow(row)">删除</el-button>
</template>
</el-table-column>
</el-table>
<el-dialog title="编辑" :visible.sync="dialogVisible">
<el-form :model="currentRow" :rules="rules">
<el-form-item label="姓名" prop="name">
<el-input v-model="currentRow.name"></el-input>
</el-form-item>
<el-form-item label="年龄" prop="age">
<el-input v-model.number="currentRow.age"></el-input>
</el-form-item>
</el-form>
<div slot="footer">
<el-button @click="cancelEdit">取消</el-button>
<el-button type="primary" @click="saveEdit">保存</el-button>
</div>
</el-dialog>
</div>
</template>
<script lang="ts">
import { defineComponent, ref } from 'vue';
export default defineComponent({
setup() {
const tableData = ref([
{ name: '张三', age: 20 },
{ name: '李四', age: 25 },
{ name: '王五', age: 30 },
]);
const currentRow = ref({ name: '', age: 0 });
const dialogVisible = ref(false);
const rules = {
name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
age: [{ required: true, message: '请输入年龄', trigger: 'blur' }],
};
const addRow = () => {
currentRow.value = { name: '', age: 0 };
dialogVisible.value = true;
};
const editRow = (row: any) => {
currentRow.value = { ...row };
dialogVisible.value = true;
};
const deleteRow = (row: any) => {
tableData.value.splice(tableData.value.indexOf(row), 1);
};
const saveEdit = () => {
const index = tableData.value.indexOf(currentRow.value);
if (index === -1) {
tableData.value.push(currentRow.value);
} else {
tableData.value[index] = currentRow.value;
}
dialogVisible.value = false;
};
const cancelEdit = () => {
dialogVisible.value = false;
};
return {
tableData,
currentRow,
dialogVisible,
rules,
addRow,
editRow,
deleteRow,
saveEdit,
cancelEdit,
};
},
});
</script>
```
在这个示例中,我们使用了`<el-dialog>`组件来实现表格的编辑功能。当用户点击添加或编辑按钮时,会打开一个弹窗,让用户输入或修改数据。表格的数据使用响应式数据来保存,当用户点击保存按钮时,会根据数据的状态来执行新增或修改操作。
希望这个例子能够对你有所帮助!
阅读全文