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

Zen coding for editplus example code description

For example, he enters: XML/HTML Code div#page>...

Can Docker become the next "Linux"?

The Linux operating system has revolutionized the...

The whole process of installing mysql5.7.22 under ARM64 architecture

MySQL download address: https://obs.cn-north-4.my...

base target="" specifies the target of the base link to open the frame

<base target=_blank> changes the target fram...

Detailed explanation of the use of redux in native WeChat applet development

premise In complex scenarios, a lot of data needs...

Detailed example of using the distinct method in MySQL

A distinct Meaning: distinct is used to query the...

Introduction to Linux compression and decompression commands

Table of contents Common compression formats: gz ...

How to manually scroll logs in Linux system

Log rotation is a very common function on Linux s...

How to use watch listeners in Vue2 and Vue3

watch : listen for data changes (change events of...

Vue realizes the logistics timeline effect

This article example shares the specific code of ...

How to implement Vue binding class and binding inline style

Table of contents Binding Class Binding inline st...

Exploration of three underlying mechanisms of React global state management

Table of contents Preface props context state Sum...

The difference and usage between div and span

Table of contents 1. Differences and characterist...

About the correct way to convert time in js when importing excel

Table of contents 1. Basics 2. Problem Descriptio...