A small Vue.js app

Removing elements from an array

In Displaying a list of tags from an array, I told my Vue app to loop through an array (tempTags) stored in data, and display each element on a dummy button.

Goal

Now I’ll add a delete method for tags, and an event listener to invoke it when the “x” button of a tag is clicked.

Breakdown

  1. Add the click event handler to the “x” button
  2. Add a removeTag method to the Vue instance

1. Add the click event handler to the “x” button

<div class="tag-buttons" v-for="tag in tempTags" >
  <button class="button-lhs">{{tag}}</button>
  <button class="button-rhs" @click="removeTag(tag)"> x </button>
</div>

Because the @click event listener (shorthand for v-on:click) is on an element inside the v-for="tag in tempTags" loop, tag here refers to the item at the current index within the tempTags array.

2. Add a removeTag method to the Vue instance

removeTag(tag) {
  this.tempTags.splice(this.tempTags.indexOf(tag), 1)
},

The JavaScript splice() array method is deleting one element from tempTags, at the indexOf() the tag that needs deleting.

If I were using the item’s index as the key with v-for, this method would look simpler, because splice() needs an array index as a parameter. I’m using the item’s value itself (tag) to identify it instead, for versatility and robustness, so I need to use indexOf(tag) to get this.

Now the “x” buttons next to the tag names are working buttons. I’ve reached the point where it makes sense to learn how to take the text and the tags the user has entered, and collect them into an object.