How to push items into an array in the data object in Vue.js?

Sometimes, we want to push items into an array in the data object in Vue.js.

In this article, we’ll look at how to push items into an array in the data object in Vue.js.

How to push items into an array in the data object in Vue.js?

To push items into an array in the data object in Vue.js, we can make a copy of the object to append to the array before we call push with it.

For instance, we write

<script>
export default {
  //...
  data() {
    return {
      queue: [],
      purchase: {
        product: null,
        customer: null,
        quantity: null,
      },
    };
  },
  methods: {
    queuePurchase() {
      this.queue.push({ ...this.purchase });
    },
    //...
  },
  //...
};
</script>

to call this.queue.push with the copy of the this.purchase object.

Making a copy of the object will mean that only the original this.purchase object when we change the properties in it rather than this.purchase and the item in the this.queue array.

Conclusion

To push items into an array in the data object in Vue.js, we can make a copy of the object to append to the array before we call push with it.