Vue User Manager - Part 5
In this step, we'll work on the 'create' portion of our CRUD app. We'll start by updating the addUser() method in the root component. Make sure to remove (or comment out) any code that is in the body of this method before we get started.
Now update the addUser() method to look like this:
addUser(){
this.selectedUserId = -1;
}
Remember that the 'key' of the user-form is bound to the selectedUserId, so by changing selectedUserId, the user-form to refresh.
The selectedUserId is also bound to the userId prop of the user-form. So when it changes, the prop will be updated to -1.
If you run the app now, and press the 'Add User' button, the app will crash because when the user-form mounts it will pass the userId (which is set to -1) into the getUserById() method of the data access component. This is not a valid user id, so the method will return undefined.
In order to prevent the crash, we need to make a very small change to the IF statement in the mounted() method of the user-form component:
mounted(){
// if the userId prop was passed in, then get the user for that ID
if(this.userId > 0){ // UPPATE THE BOOLEAN EXPRESSION TO LOOK LIKE THIS
const user = uda.getUserById(this.userId);
// initialize all the data members declared for this component
this.firstName = user.firstName;
this.lastName = user.lastName;
this.email = user.email;
}
}
Notice that the boolean expression of the IF statement is now checking to make sure that the userId prop is greater than 0. If so, then it will use the data access component to get the user. If not, it will do nothing, which will result in the data members of the component (firstName, lastName, and email) retaining their default values, which are empty strings.
The INPUT elements are bound to the data members (with v-model), so they will display empty strings. As you enter information into the INPUTs, the v-model will automatically update the data members.
When you submit the form, the handleSubmit() method will create a new 'user' object and 'emit' it to the parent. Let's make a change to the parent so that it knows whether to update an existing user, or insert a new one. So, in the root component, update the handleUserFormSubmitted() method to look like this:
handleUserFormSubmitted(user){
if(user.id > 0){
uda.updateUser(user);
}else{
uda.insertUser(user);
}
this.users = uda.getAllUsers();
}
Now run the app, and create a new user or two!