Thought leadership from the most innovative tech companies, all in one place.

How to Add an Item to an Array in Vue.js

A quick guide on how to easily add an item to a state array in Vue.js

image

Add Item to Array With push() Method

To add an item to an array in Vue.js, 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>

image

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

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>

image

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

Originally published at codingbeautydev.com

11 Amazing New JavaScript Features in ES13

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

image

Sign up and receive a free copy immediately.




Continue Learning