vue snippet

Vue.js Snippets – Delete Item from List


There are a few common operations that are performed on lists: add a new item, search through the list, and deleting an item from a list. The snippet below shows how to delete an item from a list.

<template>
  <div>
    <ul>
      <li v-for="(item, index) in list" :key="index">
        <span>{{ item }}</span>
        <button @click="deleteFromList(index)">Delete</button>
      </li>
    </ul>
  </div>
</template>

<script>
export default {
  data() {
    return {
      list: ["john", "doe", "jane"]
    };
  },
  methods: {
    deleteFromList(index) {
      this.list.splice(index, 1);
    }
  }
};
</script>

list is an array of names. In the <template>, we render the list using v-for. For each list item, we display the name along with a button. Each button has a click listener which triggers the method deleteFromList(). The method receives the index of the item and deletes the item from the list using Array.splice().

Use Cases

  • Delete from cart (E-commerce)

Share on social media

//