Adding or removing elements from a list dynamically using VueJS?


Vue can be defined as a progressive framework for building the user interfaces. It has multiple directives that can be used as per the user needs. The basic core library is mainly focused on building the view layer only and is also easy to pick up other libraries or integrate with them.

We can dynamically add or remove elements from a list in VueJS using the v-model directive. All the possibilities are binded to a single channel while using this directive. When the user selects an option out of several options, the same will be added to the list. On de-selecting the element it will be dynamically removed from the list. The below list shows the addition and deletion of elements dynamically.

Syntax

Following is the syntax to use the v-model directive −

<input type="text" id="name" v-model="username">
<p>Hello, {{ username }}!</p>

Here, the value of the username data property is bound to the value of the input element using the v-model directive. When the user types in the input field, the value of username will be updated automatically. The updated username value is then used in the template to display a personalized greeting message to the user.

The v-model directive can also be used with other form elements like checkboxes, radio buttons, and select elements to bind their values to Vue.js data properties.

Example

Copy paste the below code snipped in your vue project and run the vue project. You shall see the below output on the browser window.

  • FileName - app.js

  • Directory Structure -- $project/public -- app.js

// Dynamically updating the list
const parent = new Vue({
   el : '#parent',
   data : {
      subjects : []
   }
})
  • FileName - index.html

  • Directory Structure -- $project/public -- index.html

<html>
<head>
   <script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
</head>
   <body>
      <div id='parent'>
         <p><strong>Choose Subjects you want to opt:</strong></p>

         <input type="checkbox" id="chemistry" value="chemistry" v-model="subjects">
            <label for="chemistry">Chemistry</label>
         <input type="checkbox" id="physics" value="physics" v-model="subjects">
            <label for="physics">Physics</label>
         <input type="checkbox" id="maths" value="maths" v-model="subjects">
            <label for="maths">Maths</label>
         <input type="checkbox" id="accounts" value="accounts" v-model="subjects">
            <label for="accounts">Accounts</label>
         <input type="checkbox" id="biology" value="biology" v-model="subjects">
            <label for="biology">Biology</label>
         <p><strong>Subjects You Like:</strong>
            {{ subjects }}
         </p>
      </div>
      <script src='app.js'></script>
   </body>
</html>

Run the following command to get the below output −

C://my-project/ > npm run serve	

Complete Code

We can club the above code into a single HTML file. It will make us run the code in HTML.

<html>
<head>
   <script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
</head>
   <body>
      <div id='parent'>
         <p><strong>Choose Subjects you want to opt:</strong></p>
         <input type="checkbox" id="chemistry" value="chemistry" v-model="subjects">
            <label for="chemistry">Chemistry</label>
         <input type="checkbox" id="physics" value="physics" v-model="subjects">
            <label for="physics">Physics</label>
         <input type="checkbox" id="maths" value="maths" v-model="subjects">
            <label for="maths">Maths</label>
         <input type="checkbox" id="accounts" value="accounts" v-model="subjects">
            <label for="accounts">Accounts</label>
         <input type="checkbox" id="biology" value="biology" v-model="subjects">
            <label for="biology">Biology</label>
         <p><strong>Subjects You Like:</strong>
            {{ subjects }}
         </p>
      </div>
      <script>
      
         // Dynamically updating the list
         const parent = new Vue({
            el : '#parent',
            data : {
               subjects : []
            }
         })
      </script>
   </body>
</html>

When you click on the check box the respective subject will be added to the list of subjects and when you uncheck the box the respective subject is removed from the list.

Example

In the below example, we demonstrate adding and removing elements dynamically from a list using HTML, CSS, and VueJS.

<!DOCTYPE html>
<html>
<head>
   <title>Dynamically Add/Remove List Items with VueJS</title>
   <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
   <style>
      ul {
         list-style: none;
         padding: 0;
      }
      li {
         display: flex;
         justify-content: space-between;
         align-items: center;
         padding: 10px;
         margin-bottom: 10px;
         border: 1px solid #ccc;
      }
      input {
         margin-right: 10px;
      }
      button {
         background-color: #ccc;
         color: #fff;
         border: none;
         padding: 10px;
         cursor: pointer;
      }
   </style>
</head>
   <body>
      <div id="app">
         <h2>Dynamically Add/Remove List Items with VueJS</h2>
         <form @submit.prevent="addItem">
            <input type="text" v-model="newItem" placeholder="Enter new item">
            <button type="submit">Add Item</button>
         </form>
         <ul>
            <li v-for="(item, index) in items" :key="index">
               <span>{{ item }}</span>
               <button @click="removeItem(index)">Remove</button>
            </li>
         </ul>
      </div>
      <script>
         new Vue({
            el: '#app',
            data: {
               newItem: '',
               items: ['Item 1', 'Item 2', 'Item 3']
            },
            methods: {
               addItem() {
                  if (this.newItem) {
                     this.items.push(this.newItem);
                     this.newItem = '';
                  }
               },
               removeItem(index) {
                  this.items.splice(index, 1);
               }
            }
         });
      </script>
   </body>
</html>

In the above example, we use v-for directive to display the elements. We define two methods - removeItem() and addItem() to remove and add elements to the list. To implement the removeItem() method, we use splice() method and for implementing addItem() method we use push() method.

In this tutorial, we learned how to add or remove elements from a list dynamically using Vue.js. We looked at two examples.

Updated on: 12-Apr-2023

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements