Vue User Manager - Part 6

In this step we'll finish off the CRUD functionality of our app by adding a 'delete' button.

First, add the following button to the template of the user-form component (you can make it a sibling of the submit button):

<input type="button" value="delete" v-if="userId > 0" @click="handleDeleteClick" />

Note that clicking the button will trigger the handleDeleteClick() method, which we have not yet defined in the component. Also note that the v-if directive is used to show the button only if you are editing user that already exists in the database. The button will not appear if you've just clicked the 'Add User' button.

Now, add this code to the 'methods' object of the user-form component: (make sure to put a comma after the handleSubmit() method):

handleDeleteClick(){
    if(confirm(`Are you sure you want to delete ${this.firstName} ${this.lastName}?`)){
        this.$emit('delete-user', this.userId);
    }
}

If the intent to delete is confirmed we are emitting a 'delete-user' event along with the id of the user to delete. The parent component will execute the delete and then refresh the user-list. You could potentionally delete the user from within the user-form, but it makes more sense to let the root component do it because it's also doing inserts and updates.

Now we need to set up the root component to listen for 'delete-user' events coming from the user-form. So, update the user-form element in the template of the root component to look like this:

<user-form 
    v-if="selectedUserId" 
    :userId="selectedUserId" 
    :key="selectedUserId" 
    @user-form-submitted="handleUserFormSubmitted"
    @delete-user="handleDeleteUser" />

It will now trigger the handleDeleteUser() method when a 'delete-user' event is emitted from the user-form.

Now add the handleDeleteUser() method to the methods object of the root component (make sure to put a comma under the previous method):

handleDeleteUser(id){
	uda.deleteUser(id);
	this.users = uda.getAllUsers();
}

If you run the app and delete a user, you'll notice that the user-form continues to display information for the user that has just been deleted. We can take care of that by setting the selectedUserId to 0. Remember that the user-form element is using the v-if method that depends on the selectedUserId. So, if the selectedUserId is a falsy value, then the user-form will not be visible. Update the handleDeleteUser() method to look like this:

handleDeleteUser(id){
    uda.deleteUser(id);
    this.users = uda.getAllUsers(); // this will refresh the user-list
    this.selectedUserId = 0; // this will hide the user-form
}