实现思路:
1.点击当前行通过row拿到当前行数据。
2.将当前行数据传给子组件。
3.子组件监听父组件传过来的数据并映射在界面。
4.点击保存将修改的值传给父组件更新表格。
5.父组件收到修改过后的值,可以通过字段判断比如id,通过 findIndex找到是哪条数据修改了,然后在更新表格数据
table.vue
<template>
<div>
<el-button @click="add">新增数据</el-button>
<el-table :data="tableData" border @cell-click="cellClick">
<el-table-column prop="name" label="名称" width="180"></el-table-column>
<el-table-column prop="age" label="年龄" width="180"></el-table-column>
<el-table-column prop="gender" label="性别" width="180"></el-table-column>
<el-table-column label="操作">
<template #default="{ row }">
<el-button type="primary" @click="edit(row)">编辑</el-button>
</template>
</el-table-column>
</el-table>
<Boundary
v-if="showEdit"
:update="person.selectedRow"
@updateTable="updateTable"
/>
</div>
</template>
<script setup>
import { ref, reactive } from "vue";
import Boundary from "./Boundary.vue";
const tableData = ref([
{ name: "张三", age: 18, gender: "男", id: 1 },
{ name: "李四", age: 20, gender: "女", id: 2 },
]);
const person = reactive({
selectedRow: "",
});
const showEdit = ref(false);
// 点击单行
function cellClick(row) {
showEdit.value = true;
person.selectedRow = { ...row };
}
// 点击编辑按钮
function edit(row) {
showEdit.value = true;
person.selectedRow = { ...row };
}
// 点击按钮在表格中新增一条数据,id递增
function add() {
tableData.value.push({
name: "",
age: null,
gender: "",
id: tableData.value.length + 1,
});
}
// 根据id找出索引
function updateTable(newData) {
const index = tableData.value.findIndex((item) => item.id === newData.id);
tableData.value.splice(index, 1, newData);
}
</script>
Boundary.vue
<template>
<div>
<input v-model="person.inputData.name" placeholder="请输入名称" />
<input v-model="person.inputData.age" placeholder="请输入年龄" />
<input v-model="person.inputData.gender" placeholder="请输入性别" />
<el-button type="primary" @click="save">保存</el-button>
</div>
</template>
<script setup>
import { ref, reactive, watch } from "vue";
const emits = defineEmits(["updateTable"]);
let props = defineProps({
update: {
type: Object,
default: {},
},
});
const person = reactive({
inputData: {
name: "",
age: "",
gender: "",
id: "",
},
});
function save() {
emits("updateTable", person.inputData);
}
// 接收表格传过来的数据
person.inputData = props.update;
// 监听父组件传过来的表格数据
watch(
() => props.update,
(val) => {
person.inputData = val;
},
{ deep: true }
);
</script>