Sometimes, we want to add a copy of a persistent object to a repeated array with Vue.js.
In this article, we’ll look at how to add a copy of a persistent object to a repeated array with Vue.js.
How to add a copy of a persistent object to a repeated array with Vue.js?
To add a copy of a persistent object to a repeated array with Vue.js, we can use the object spread operator.
For instance, we write:
<template>
<button @click="addItem">add</button>
<div>{{ items }}</div>
</template>
<script>
export default {
name: "App",
data() {
return {
newItem: { name: "" },
items: [],
};
},
methods: {
addItem() {
this.items.push({ ...this.newItem });
},
},
};
</script>
to add a button that calls addItem
when we click it.
In addItem
, we call this.items.push
with a shallow clone of this.newItem
that we created with the object spread operator.
Therefore, when we click on add, we see a new entry of items
added.
Conclusion
To add a copy of a persistent object to a repeated array with Vue.js, we can use the object spread operator.