The practical process of login status management in the vuex project

The practical process of login status management in the vuex project

tool:

Install Vue.js devtools in chorme browser for easy debugging

Login scenario:

The user's current login status may sometimes be displayed in the page navigation or other places. The status can be divided into: not logged in, logging in (loading), successfully logged in and displaying the user name.

Some pages can be browsed by users without logging in, but some pages must be logged in before they can be browsed.

practice:

Scenario 1: Thinking and Practice

Creating a data store with vuex

//Create a new store directory under the src directory and create index.js as follows //Create a data warehouse import Vuex from 'vuex';
import vue from 'vue';
import loginUser from 'loginUser.js'
Vue.use(Vuex)

const store = new Vuex.Store({
    modules: { //modules can put different states in a separate object loginUser //Whether you are logging in},
    strict: true, //Only allow state changes through mutations });

Set the login status loading and the current logged in user user

//Create a loginUser.js and create its state/mutations/actions

//The state that needs to be maintained state: {
       loading: false, //Login status user: null, //Currently logged in user},
//Calculated property getters: {
       status(state) {
           if (state.loading) {
               return 'loading'
           } else if (state.user) {
               return 'login'
           } else {
               return 'unLogin'
           }
       }
   },
 
 //Change loading and user status mutations: {
       //Set loading
       setLoading(state, msg) {
           state.loading = msg
       },
       //Set user setUser(state, msg) {
           state.user = msg
       }
   },
 
 //Submit the changed status in actions actions: {
       //The login method ctx is equivalent to store
       async login(ctx, msg) {
           //Set the login status to true
           ctx.commit("setLoading", true)
           const result = await xxxapi.login(msg.loginId, msg.loginPassword)
           if (result) {
               //Login successful ctx.commit('setUser', result)
               //After successful login, the login status is set to false
               ctx.commit('setLoading', false)
           }
           //Return whether the login is successful return result
       },
       //Judge whether you have logged in async isLogin(ctx) {
           //Logging in ctx.commit('setLoading', true)
           //Call the interface to see if it is logged in const result = await xxxapi.isLogin();
           ctx.commit('setUser', result);
           ctx.commit('setLoading', false)
       },
       //Logout async logout(ctx) {
           ctx.commit('setLoading', false)
           await xxxapi.logout();
           ctx.commit('setUser', null);
           ctx.commit('setLoading', false)
       }
   },

Page usage:

When logging in, there is a login button, and we can get the status of the button in the Vuex warehouse

<button :disabled="loading">{{ loading ? 'loading...' : 'Log in' }}
</button>
computed: {
//Encapsulate loading in computed, so you don’t have to write this.$store.state.loginUser every time you call it. // loading() {
    // return this.$store.state.loginUser.loading;
    // }
    // Optimization // Auxiliary function // import {mapState} from "vuex"
    ...mapState({
      loading: (state) => state.loginUser.loading
    })
  }

Dispatching action when submitting when clicking the button

async handleSubmit() {
      const result = await this.$store.dispatch("loginUser/login", {
        loginId: this.loginId,
        loginPassword: this.loginPassword
      });
      if (result) {
        // Login successful route jump const path = this.$route.query.url || '/'
        this.$router.push(path)
      }
    },

Switch the login status in the page navigation [loading/login/unlogin]

  <!-- Display page login status-->
<span v-if="status === 'loading'">Logging in, please wait...</span>
​
<template v-else-if="status === 'login'">
    <span>Currently logged in user {{user.name}}</span>
    <span @click="handleLogout">Logout</span>
</template>
​
<router-link to="/login" v-else>
        Login</router-link>
  computed: {
...mapGetters("loginUser", ["status"]),
...mapState("loginUser", ["user"]),
}

Change status on logout

async handleLogout(){
    await this.$store.dispatch("loginUser/logout")
    //Jump to the login page this.$route.push(/xxx)
},

The login status needs to be checked every time the page is refreshed, and this needs to be determined in main.js, which is when vue is created.
store.dispatch('loginUser/isLogin')

Scenario 2: Thinking and Practice

Refer to the permission settings in the background project

Overall design:

After refreshing the page, first check the login status in the Vuex warehouse –> Navigation guard (router.beforeEach) detects whether this page is logged in by judging the parameters set in meta

You need to log in to view --> page rendering.

Overall logic:

1. When entering the page, determine whether this page requires login to view

2. Determine the login status. There are three states as follows:

  1. If you are already logged in, go directly to the page you want to go to.
  2. If the user is not logged in, go to the login page and let the user log in.
  3. If the status is loading, pass in the path of the page you want to go to, and monitor the changes in the user's login status in the Vuex warehouse on the loading page. After monitoring the status changes, it is either logged in or not logged in, and then go to step 1 to determine whether login permission is required.

practice:

Set meta in the router. If auth is true, you need to log in to access.

//import Home from "./xx/xx.vue" in routes.js
export default[
{
      path:"/home",
    component:Home,
    meta: {
      auth: true, //pages that require permissions to access}
}
]
Set the route guard in index.js router.beforeEach((to, from, next) => {
    if (to.meta.auth) {
        // Login permission is required to access const result = store.getters["loginUser/status"]
        if (result === 'loading') {
            // Loading status, I don't know if you are logged in // Jump to a page that is logging in, and monitor whether the login is successful on the page, otherwise it will stay here forever // And when the route jumps, you must record where you came from before, otherwise you don't know which page to jump to next({
                path: '/loading', //Go to the [Logging in] page query: {
                    url: to.fullpath
                }
            })
        } else if (result === 'login') {
            // Login successfulnext();
        } else {
            // Not logged in this.$message.info('You need to log in');
             next({
                path: '/login', //Go to the [Logging in] page query: {
                    url: to.fullpath
                }
            })
        }
    } else {
        //Pages that can be accessed without login permission next()
    }
})

Monitor the current status on the login page

created() {
  this.unWatch = this.$watch(() => this.$store.getters["loginUser/status"], (status) => {
    console.log('current status', status);
    if (status !== 'loading'){
      this.$router.push(this.$route.query.url || '/home').catch(() => {}
    }
  }, {
    immediate: true
  })
},
destroyed() {
  //Cancel monitoring this.unWatch()
}

Summarize

This is the end of this article about login status management in vuex projects. For more relevant vuex login status management content, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Detailed explanation of Vuex management login status
  • Example code for saving user login status in Vue
  • How to register and keep logged in in Vue
  • How to keep the user logged in in the Vue project (localStorage+vuex keeps the status after refreshing the page)

<<:  Advantages and disadvantages of MySQL indexes and guidelines for creating indexes

>>:  Detailed explanation of the use of DockerHub image repository

Recommend

Mobile web screen adaptation (rem)

Preface I recently sorted out my previous notes o...

Detailed explanation of CSS3 elastic expansion box

use Flexible boxes play a vital role in front-end...

jenkins+gitlab+nginx deployment of front-end application

Table of contents Related dependency installation...

Nginx cache files and dynamic files automatic balancing configuration script

nginx Nginx (engine x) is a high-performance HTTP...

Bootstrap 3.0 study notes page layout

This time we will mainly learn about layout, whic...

Linux system calls for operating files

Table of contents 1. Open the file Parameter Intr...

How to quickly log in to MySQL database without password under Shell

background When we want to log in to the MySQL da...

Analysis of Linux Zabbix custom monitoring and alarm implementation process

Target Display one of the data in the iostat comm...

Implementing carousel with native JavaScript

This article shares the specific code for impleme...

Implement full screen and monitor exit full screen in Vue

Table of contents Preface: Implementation steps: ...

Detailed explanation of the usage of two types of temporary tables in MySQL

External temporary tables A temporary table creat...

Use of Linux watch command

1. Command Introduction The watch command execute...