Vue Add Item to Object: In Vue, adding an item to an object is a straightforward process that involves creating a new key-value pair. The key represents the name of the property, while the value represents the data that you want to assign to that property.
How can I add a new item to an object in Vue js?
This code defines a method called “addItem” within a Vue.js component. The method is triggered when a user wants to add a new item to a list of items. It checks if the new item has a non-empty id and name, and if so, adds it to the end of the “items” array. It then clears the input fields for id and name, ready for the user to add another item. This code assumes that there is a “newItem” object in the component’s data that stores the id and name of the new item being added, and an “items” array that contains the existing items in the list.
Vue Add Item to Object Example
<div id="app">
<input v-model="newItem.id" type="text" placeholder="Enter ID" />
<input v-model="newItem.name" type="text" placeholder="Enter Name" />
<button @click="addItem">Add Item</button>
<ul>
<li v-for="(item, index) in items" :key="index">{{ item.id }}: {{ item.name }}</li>
</ul>
</div>
<script type="module">
const app = Vue.createApp({
data() {
return {
items: [],
newItem: {
id: "",
name: "",
},
};
},
methods: {
addItem() {
if (this.newItem.id !== "" && this.newItem.name !== "") {
this.items.push({
id: this.newItem.id,
name: this.newItem.name,
});
this.newItem.id = "";
this.newItem.name = "";
}
},
},
});app.mount("#app");
</script>