การแก้ไขข้อมูลของคอมโพเนนต์แบบรีแอคทีฟใน Vue
ตอนนี้เรามาลองนำการแก้ไขข้อมูลของ
คอมโพเนนต์ลูกของเราไปใช้กัน
เริ่มต้นที่คอมโพเนนต์หลัก
สร้างเมธอดสำหรับเปลี่ยนข้อมูลผู้ใช้ตาม id ของเขา:
methods: {
change(id, name, surn) {
this.users = this.users.map((user) => {
if (user.id === id) {
user.name = name;
user.surn = surn;
}
return user;
});
}
}
สร้างคอมโพเนนต์ในลูป พร้อมส่ง
พารามิเตอร์ชื่อ นามสกุล id
และเมธอดสำหรับการเปลี่ยนแปลงให้:
<template>
<User
v-for ="user in users"
:id ="user.id"
:name ="user.name"
:surn ="user.surn"
:key ="user.id"
@change="change"
/>
</template>
กำหนดอีเวนต์ที่จะ emit ในการตั้งค่า
emits ของคอมโพเนนต์ลูก:
props: {
id: Number,
name: String,
surn: String,
},
emits: ['change'],
ตอนนี้ในคอมโพเนนต์ลูก สร้าง พร็อพเพอร์ตี้ที่กำหนดโหมดการทำงานของ คอมโพเนนต์ แสดงผลหรือแก้ไข:
data() {
return {
isEdit: false,
}
}
สร้างพร็อพเพอร์ตี้สำหรับสนับสนุน การทำงานของอินพุตสำหรับการแก้ไขด้วย:
data() {
return {
isEdit: false,
newName: '',
newSurn: '',
}
}
ตั้งค่าให้ค่าเริ่มต้นของ พร็อพเพอร์ตี้เหล่านี้ถูกนำมาจากพร็อพส์:
data() {
return {
isEdit: false,
newName: this.name,
newSurn: this.surn,
}
}
สร้างเมธอดที่จะ เปิดโหมดแก้ไข:
methods: {
edit() {
this.isEdit = true;
}
}
สร้างเมธอดที่จะ บันทึกข้อมูลที่แก้ไขแล้ว พร้อมปิด โหมดแก้ไข:
methods: {
save() {
this.isEdit = false;
this.$emit('change', this.id, this.newName, this.newSurn);
}
}
สร้างเทมเพลตของคอมโพเนนต์ลูก:
<template>
<template v-if="!isEdit">
{{ name }}
{{ surn }}
<button @click="edit">
edit
</button>
</template>
<template v-else>
<input v-model="newName">
<input v-model="newSurn">
<button @click="save">
save
</button>
</template>
</template>
นำการแก้ไขข้อมูลของคอมโพเนนต์
Employee ไปใช้