How to Add an Item to an Array in Vue

Add Item to Array With push() Method

To add an item to an array in Vue, call the push() method in the array with the item as an argument. The push() method will add the item to the end of the array.

For example:

<template>
  <div id="app">
    <button @click="addFruit">Add fruit</button>
    <ul>
      <h2
        v-for="(fruit, i) in fruits"
        :key="i"
      >
        {{ fruit }}
      </h2>
    </ul>
  </div>
</template>

<script>
export default {
  data() {
    return {
      fruits: ['Orange', 'Apple'],
    };
  },
  methods: {
    addFruit() {
      this.fruits.push('Banana');
    },
  },
};
</script>
Clicking the button adds a new fruit item.
Clicking the button adds a new fruit item.

The Array push() method adds one or more items to the end of an array and returns the length of the array.

We use the v-for Vue directive to display the items in the array. These rendered items are automatically updated in the view when the array is modified with push().

Add Object Item to Array in Vue

We can use the same approach to add an object to an array and display more complex data. We just have to make sure that we render the properties of each object in the array, not the object itself.

<template>
  <div id="app">
    <button @click="addFruit">Add fruit</button>
    <ul>
      <h2
        v-for="(fruit, i) in fruits"
        :key="i"
      >
        <!-- Render "name" and "amount" properties -->
        {{ fruit.name }} ({{ fruit.amount }})
      </h2>
    </ul>
  </div>
</template>

<script>
export default {
  data() {
    return {
      fruits: [
        { name: 'Orange', amount: 3 },
        { name: 'Apple', amount: 5 },
      ],
    };
  },
  methods: {
    addFruit() {
      // Add object item to array
      this.fruits.push({ name: 'Banana', amount: 4 });
    },
  },
};
</script>
Clicking the button adds a new fruit item with a certain amount.
Clicking the button adds a new fruit item with a certain amount.

Like before, the list automatically updates in the view when a new object item is added to the array.



11 Amazing New JavaScript Features in ES13

This guide will bring you up to speed with all the latest features added in ECMAScript 13. These powerful new features will modernize your JavaScript with shorter and more expressive code.

11 Amazing New JavaScript Features in ES13

Sign up and receive a free copy immediately.

Leave a Comment

Your email address will not be published. Required fields are marked *