Button to remove objects from array in Vue
Let's now implement a button to delete data from an array of objects. Let's get started with the implementation. Let's have the following array:
data() {
return {
users: [
{
id: 1,
name: 'name1',
surn: 'surn1',
},
{
id: 2,
name: 'name2',
surn: 'surn2',
},
{
id: 3,
name: 'name3',
surn: 'surn3',
},
]
}
}
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>
Let's make a button for deleting in each list item. In this button, we will bind a method, the parameter of which will be id of the array element that we are going to delete:
<template>
<ul>
<li v-for="user in users" :key="user.id">
{{ user.name }}
{{ user.surn }}
<button @click="removeItem(user.id)">remove</button>
</li>
</ul>
</template>
We implement deletion in the removeItem method:
methods: {
removeItem: function(id) {
this.users = this.users.filter((user) => {
return user.id !== id;
})
}
}
The following array of employee data is given:
data() {
return {
users: [
{
id: 1,
name: 'name1',
salary: 100,
age: 30,
},
{
id: 2,
name: 'name2',
salary: 200,
age: 40,
},
{
id: 3,
name: 'name3',
salary: 300,
age: 50,
},
],
}
}
Display employee data as an HTML table. Create a column with links to delete employees.