实现思路:
5.父组件收到修改过后的值,可以通过字段判断比如id,通过 findIndex找到是哪条数据修改了,然后在更新表格数据
<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>
<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>
原文地址:https://blog.csdn.net/m0_63701303/article/details/134573676
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如若转载,请注明出处:http://www.7code.cn/show_2917.html
如若内容造成侵权/违法违规/事实不符,请联系代码007邮箱:suwngjj01@126.com进行投诉反馈,一经查实,立即删除!
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。