Form for editing an array of objects in Vue
Let's now implement editing of the elements of the object array. Let's make a button for this, when clicked, a form for editing will appear in the list item. After filling out the form, we will click the save button and the changes will be saved in the array, and the form will be removed.
Let's get to the implementation. In the array of objects, we need to add another field to each object, containing the user's state, showing or editing:
data() {
return {
users: [
{
id: 1,
name: 'name1',
surn: 'surn1',
isEdit: false,
},
{
id: 2,
name: 'name2',
surn: 'surn2',
isEdit: false,
},
{
id: 3,
name: 'name3',
surn: 'surn3',
isEdit: false,
},
]
}
}
Let's output the contents of the array as a list:
<template>
<ul>
<li v-for="user in users" :key="user.id">
{{ user.name }}
{{ user.surn }}
</li>
</ul>
</template>
Now let's separate the display mode and the editing mode:
<template>
<ul>
<li v-for="user in users" :key="user.id">
<template v-if="!user.isEdit">
{{ user.name }}
{{ user.surn }}
<button @click="edit(user)">
edit
</button>
</template>
<template v-else>
<input v-model="user.name">
<input v-model="user.surn">
<button @click="save(user)">
save
</button>
</template>
</li>
</ul>
</template>
We implement the methods:
methods: {
edit(user) {
user.isEdit = true;
},
save(user) {
user.isEdit = false;
},
}
Modify the task from the previous lesson so that there is a column with links to edit each employee.