<template>
<el-table :data="tableData" style="width: 100%">
<el-table-column prop="date" label="日期" width="180"> </el-table-column>
<el-table-column prop="name" label="姓名" width="180"> </el-table-column>
<el-table-column label="操作" width="180">
<template #default="{ row }">
<el-button size="small" @click="handleEdit(row)">编辑</el-button>
</template>
</el-table-column>
</el-table>
<el-dialog v-model="dialogVisible" title="编辑数据">
<el-form :model="editForm">
<el-form-item label="日期">
<el-input v-model="editForm.date" autocomplete="off"></el-input>
</el-form-item>
<el-form-item label="姓名">
<el-input v-model="editForm.name" autocomplete="off"></el-input>
</el-form-item>
</el-form>
<template #footer>
<span class="dialog-footer">
<el-button @click="dialogVisible = false">取消</el-button>
<el-button type="primary" @click="updateData">确定</el-button>
</span>
</template>
</el-dialog>
</template>
<script setup>
import { ref } from 'vue';
const tableData = ref([
{ date: '2021-05-03', name: 'Tom' },
{ date: '2021-05-02', name: 'Jerry' },
// ...更多数据
]);
const dialogVisible = ref(false);
const editForm = ref({});
const handleEdit = (row) => {
dialogVisible.value = true;
editForm.value = { ...row };
};
const updateData = () => {
// 更新逻辑,例如发送请求到后端更新数据库
// 前端更新tableData
const index = tableData.value.findIndex(item => item.date === editForm.value.date);
if (index !== -1) {
tableData.value[index] = { ...editForm.value };
}
dialogVisible.value = false;
};
</script>
这个例子展示了如何在Vue 3和Element Plus中实现一个简单的表格数据编辑功能。用户可以点击每行的“编辑”按钮,打开一个对话框来修改数据。修改完成后,点击确定按钮会更新表格数据和对话框状态。这个例子简洁明了,并且包含了注释,有助于理解其核心功能。