I'm currently working on implementing two components, one acting as the parent and the other as the child. In the parent component, I have set up the data attribute like this...
data () {
return {
users: [],
}
}
The users array within the parent component gets populated upon button click, and I am sharing this array with the child component. The issue arises when the child component attempts to add a user to this list - it works in terms of adding values to the passed-in props, but since the users array is declared under data in the parent, the component refreshes causing me to lose my previously added users. Is there a pattern or approach that would allow me to keep the existing values in the users array while also enabling additions from the child component?
Apologies if this query seems trivial, as I mentioned earlier, I am still quite new to this...
Edit: Here is the code for the parent component:
<template>
<div id="app">
<div>
<button v-on:click="display()">Display users</button>
<button v-on:click="displaySingleUserInput = !displaySingleUserInput">Add user</button>
<div>
</div>
<ul v-if="errors && errors.length">
<li v-for="error of errors">
{{error.message}}
</li>
</ul>
</div>
<add-user v-on:submit_user="addUser" v-show="displaySingleUserInput"></add-user>
<user-list v-bind:users="users"></user-list>
</div>
</template>
<script>
import axios from 'axios';
import UserList from './components/UserList';
import AddUser from './components/AddUser';
export default {
components: {
'user-list': UserList,
'add-user': AddUser
},
name: 'app',
data () {
return {
users: [],
errors: [],
displaySingleUserInput: false
}
},
methods: {
display: function(string)
{
axios.get(`users.json`)
.then(response => {
// JSON responses are automatically parsed.
this.users = response.data.users
})
.catch(e => {
this.errors.push(e)
})
},
addUser: function(id) {
this.users.push({firstname: "John", lastName: 'Jones'})
},
}
}
</script>
Child component:
<template>
<div id="singleUserAdd">
<form id=addUser aria-label="single user add">
<button v-on:click="submit()">Submit</button>
<button>Cancel</button>
</form>
</div>
</template>
<script>
export default {
data() {
return {
}
},
methods: {
submit: function() {
this.$emit('submit_user', 1)
}
}
}
</script>