Button to remove array element in Vue
Let's make a button for reactively deleting items from a list. Let's start implementing it. Let's say we have an array:
data() {
return {
items: ['a', 'b', 'c', 'd', 'e'],
}
}
Let's output the contents of the array as a list:
<template>
<ul>
<li v-for="(item, index) in items" :key="index">
{{ item }}
</li>
</ul>
</template>
Let's make a delete button in each list item. In this button, we'll bind a method whose parameter will be the number of the array element we're going to delete:
<template>
<ul>
<li v-for="(item, index) in items" :key="index">
{{ item }}
<button @click="removeItem(index)">remove</button>
</li>
</ul>
</template>
We implement deletion in the removeItem method:
methods: {
removeItem: function(index) {
this.items.splice(index, 1);
}
}
Given an array. Print the elements of this array as a list ul. Make it so that when you click on any li, it is removed from the list.