{{announcement.body}}
{{announcement.title}}

State Management, Modal Dialog, and Simple Spinners in Vue

DZone 's Guide to

State Management, Modal Dialog, and Simple Spinners in Vue

In this post, we'll talk about how to use state management, spinner with conditions, and modal dialogs when saving data in Vue.

· Web Dev Zone ·
Free Resource

This blog post is about how to use state management, spinner with conditions, and modal dialogs when saving data in Vue. We will explore along an implementation in the #BlueCloudMirror project. Maybe this can save you some time, if you plan to do the same.

Let’s start with my motivation. We want to improve our #BlueCloudMirror game UI. If you saved your scores data in the previous version, you were routed back to start game page. You received no information, if storing your data was successful in the highscores list.

In the new UI you can see the saving progress and you get confirmation when your data is saved, as you can see in the gif below.

blue-cloud-mirror-save

To understand how this works in Vue, we need to touch the following topics:

We will use the Results.vue and State.ts source code files from the #BlueCloudMirror GitHub project, to see how it works in the #BlueCloudMirror game.

Now, let’s look at what the implementation needs to do in order to save scores' data.

  • Pressing the save-scores button.
  • Showing the spinner during the saving progress.
  • Saving the data in the scores-service.
  • Hiding the spinner when the saving is done.
  • Showing a modal dialog for confirmation.

In the following sequence diagram, we get a high-level overview of how the code works for these steps.

vue-09-all-state

How to Use State Management

We need state management to show the spinner when the saving is in process. Vuex provides state management, for details examine the Vuex state guide.

The relevant files in the #BlueCloudMirror project are:

  • Store.ts file,which does the state management.
  • Results.vue,which consumes the states to display the spinner.

To handle the states we use mutations in Vue. The behavior of mutations are like events, for more information, take a look at this post by Vue school.

The gif shows the state in the mutation. Note: If you want to know how to configure Vue for debugging, just take a look at the cookbook for debugging in VS Code.

vue-recording-state

The starting point for using states is always setting an initialization. We put our initialization for the saving state into mounted of the Results.vue file, because, during the instantiation of the results page, the code inside mounted will be executed. For more details about mounted please take a look into the Lifecycle-Diagram for Vue.

Inside the mutation, the saving status is set to false using the commit(“setSavingStatus”, false)method of the Vue store. Next, you will see the relevant code and a small sequence diagram for the initialization.

Here is the code from the Results.vue file,

mounted() {     
  var gameResult = this.getDurationWithPenalties();     
  this.$store.commit("setTotalTime", gameResult);     
  this.$store commit("setSavingStatus", false);

And here is the sequence diagram.

vue-01-init-state

Now we take a look into the code of the mutation implementation and the state definition inside the Store.ts file.

mutations:{ setSavingStatus(state, payload) 
           { state.saving.status = payload;}      
... 
state:{saving:{status:false} 
...

With this code, we can easily change the state inside the v-button event method and set the right value for the saving status in our Vue store. The simplified sequence diagram shows how this works inside the code. Remember the gif from earlier.

vue-02-spinner-state

Inside the onSaveScore event method from the Results.vue file, we change the saving status to the correct value when it is needed.

methods:
    ...
    onSaveScore() {
        ...
        this.$store.commit("setSavingStatus", true);

        axiosService
        .post(this.$store.state.apis.scores.url, {
            firstName: firstName,
            lastName: lastName,
            gameDate: this.$store.state.currentGame.id,
            score: this.$store.state.currentGame.totalTimeWithPenalties
        })
        .then(function(response) {

            that.$store.commit("setSavingStatus", false);

            that.message = "Hello " + firstName + ", your scores data is stored. Take a look in the highscore list.";
            that.showModal();
        })
        .catch(function(error) {
                console.log("error save scores", error);
                ...

How to Use Conditions in the Vue Template

Now we know the saving state, it is time to display the spinner depending on the state. To do this, we need a v-if condition which uses a computed property. The following code shows the definition of computed property in the Results.vue file.

Computed: 
isSavingStatus: function(){ 
  return this.$store.state.saving.status; },

To control the display of the spinner we use a v-if condition inside the template. Here you can see the relevant code in the Results.vue file, during the saving progress.

<template>
...
 v-if="isSavingStatus == true" 
 class="loader">
...
</template>

How to Use a Modal Dialog

To show the confirmation for successfully saved data, we use a modal dialog in the Results.vue file. The layout of the dialog is defined in the template. To activate the dialog we are using methods. For more details please take a look into modals in the Vue bootstrap documentation.

Here you can see the relevant code for the show and hide methods with the reference ID ‘modalDialog’ of our code in the template.

methods:{   
  ...   
  showModal() {   this.$refs['modalDialog'].show();   },   
  hideModal() {   this.$refs['modalDialog'].hide();   },   
  ...

That is the layout for our modal dialog inside the template.

<b-modal ref="modalDialog" hide-footer title="Information">
<div>
{{message}}
</div>
<b-btnclass="mt-3" @click="hideModal">Close</b-btn>
</b-modal>

If the saving progress finished successfully, the showModal method will be called from the event method onSaveScore. You can see the modal event information in the gif below.

vue-recording-modal.gif

In the following source code of the onSaveScore event method, the modal dialog is invoked with the showModal method we defined before:

methods:
    ...
    onSaveScore() {
        ...
        this.$store.commit("setSavingStatus", true);

        axiosService
        .post(this.$store.state.apis.scores.url, {
            firstName: firstName,
            lastName: lastName,
            gameDate: this.$store.state.currentGame.id,
            score: this.$store.state.currentGame.totalTimeWithPenalties
        })
        .then(function(response) {

            that.$store.commit("setSavingStatus", false);

            that.message = "Hello " + firstName + ", your scores data is stored. Take a look in the highscore list.";
            that.showModal();
        })
        .catch(function(error) {
                console.log("error save scores", error);
                ...

This was all about the usage of state management, spinners with conditions, and modal dialog when saving data in Vue.

I hope this was useful for you!

Cheers,

Thomas

Topics:
vue ,javascript ,web dev ,vue.js tutorial ,web application data

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}