How to add values to an array in VueJS?

Hi Friends 👋,

Welcome To SortoutCode! ❤️

To add new value to the array in VueJS.We are going to use the push() method. Using the push() method we can add one or more values to the end of the array and you get the new length of your array.

Today I am going to show you How to add values to an array in VueJS?

Table of contains

  • Setup the Vue.js
  • Add values to the array

Let’s start today’s tutorial How do I add values to an array in VueJS?

Setup the Vue.js

First, we have to install the Vue project, I had installed the vueJS in my system. If you haven’t installed or have any problem with installation you can follow this article, which will show you step by step process of installation.

How to Install the VueJS project?

Add values to the array

We are going to take an example to add value to your existing array. First, we are going to define the dayNames array in the data() function. Added the addDay() methods and in this method, we have defined the newDay with Sunday value. When addDay method is called newDay value will be added to the dayNames array using the push() method.

Using the v-for directive we have iterated dayNames array and displayed it in the list. And also : key is used to bind with a unique key for each day. This will help Vue.js to optimize the rendering when a new value is added to the dayNames array.

<template>
  <div>
    <h1>Welcome to sortoutcode.com</h1>
    <div>
      <ol>
        <li v-for="(day, index) in dayNames" :key="index">{{ day }}</li>
      </ol>
      <button @click="addDay">Add Day</button>
    </div>
  </div>
</template>
<script>
export default {
  name: "FirstComponent",
  data() {
    return {
      dayNames: [
        "Monday",
        "Tuesday",
        "Wednesday",
        "Thursday",
        "Friday",
        "Saturday",
      ],
    };
  },
  methods: {
    addDay() {
      var newDay = "Sunday";
      this.dayNames.push(newDay);
    },
  },
};
</script>

For now, let’s check the output.

Add value to array in vuejs

All the best 👍.

Follow me on Twitter