This code snippet illustrates how to delete an item from a list in Vue

Deleting an item from a list is a common operation in many web applications, particularly in scenarios like removing an item from a shopping cart in e-commerce websites.

Table of Contents

Code Snippet:

<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>

Explanation

In this code, list is an array of names. Within the <template>, the list is rendered using Vue’s v-for directive. For each item in the list, the name is displayed along with a ‘Delete’ button.

The button has a click listener which triggers the deleteFromList() method when clicked.

The deleteFromList() method receives the index of the item and deletes it from the list using the Array.splice() method.

Usage

This component can be incorporated into any Vue.js project where there’s a need to delete items from a list. To use it, simply replace the list data property with your own data and adjust the template markup as per your application’s styling and structure requirements.

Example

A common use case for this functionality is deleting items from a shopping cart in e-commerce applications. When the ‘Delete’ button next to an item in the cart is clicked, the deleteFromList() method can be invoked to remove the item from the list of items in the cart.

Conclusion:

This Vue.js code snippet provides a simple and effective way to delete an item from a list.

It is an essential operation that’s commonly used in many web applications, especially in scenarios like e-commerce where users frequently add and remove items from their shopping carts.

The snippet can be easily adapted and integrated into your Vue.js application as per your specific requirements.