Vue Js Add JSON to array by user input:In Vue.js, when adding JSON to an array based on user input using the spread operator (...
), a shallow copy of the this.data
object is created. The spread operator allows you to extract the properties and values from the this.data
object and create a new object with the same properties and values. By using the spread operator, you ensure that any modifications made to the copied object do not affect the original this.data
object. This is useful when adding multiple instances of the this.data
object to the array, as each instance will have its own independent values.
How can a user add JSON data to an array using Vue.js through user input?
The given code snippet is an example of how to add JSON data to an array in Vue.js using user input. The HTML part consists of input fields for name, role, and email, along with a button to add the entered data. The entered values are bound to the data
object using the v-model
directive.
The JSON data entered by the user is stored in the dataArray
array when the “Add Data” button is clicked. The addData
method is responsible for pushing a copy of the data
object into the dataArray
, and then resetting the input fields to empty values. The added data is displayed as a list using the v-for
directive
Vue Js Add JSON to array by user input Example
<div id="app">
<input v-model="data.name" type="text" placeholder="Enter name" />
<input v-model="data.role" type="text" placeholder="Enter role" />
<input v-model="data.email" type="email" placeholder="Enter email" />
<button @click="addData">Add Data</button>
<ul>
<li v-for="(item, index) in dataArray" :key="index">{{ item }}</li>
</ul>
</div>
<script type="module">
const app = new Vue({
el: "#app",
data() {
return {
data: {
name: 'John',
role: 'Developer',
email: 'john@gmail.com'
},
dataArray: []
};
},
methods: {
addData() {
this.dataArray.push({ ...this.data });
this.data.name = '';
this.data.role = '';
this.data.email = '';
}
}
});
</script>