The solution of vue that the same browser only allows one account to be logged in at the same time - real project use

The previous article introduced the solution that the same browser only allows one account to log in at the same time.
This article records the final solution determined in the project.

Scenario: In the same browser, after logging in to account A, open a new tab page, log in to account B, user A will be forced to return to the login page; this
scenario should be encountered by many front-end partners, and I will share my project below The actual method used;
logical thinking: After a user successfully logs in, record the token or id, store it in local or cookies, and submit the token or id data to vuex synchronously. On the new tab page, log in to user B, compare B's token with the toekn in user A's vuex, and if they are inconsistent, A will be forced to return to the login page. In the App.vue file, use document.addEventListener('visibilitychange', function(){}j to listen to open a new tab page

Landing page:

 loginValidate() {
    
    
    this.$refs['loginForm'].validate(async valid => {
    
    
      if (valid) {
    
    
        this.loading = true
        try {
    
    
          const res = await login({
    
    loginForm }))
          if (res?.data) {
    
    
           // 存储token到cookies
            this.setToken(res.data.AuthToken)
            //设置token数据给到vuex
            this.$store.commit('token/setTokenInfo', res.data.AuthToken)
          }
        } catch (error) {
    
    
        }
      } else {
    
    
        return false
      }
    })
  }

  setToken(token: string) {
    
    
    Cookies.set('yi-token', token)
  }

store/modules/token.js
Note: Here, a default value is set for the tokenInfo in the state: the token in the cookies, to avoid the problem that the vuex data will be lost when the user clicks the browser refresh button. This processing is really amazing, because there is another business logic in the project: click to open a new tab to view the report, and the token must still be included in vuex.
(Two situations where vuex data will be lost: 1. Click the browser refresh button; 2. Open a new tab page;)

import Cookies from 'js-cookie'
export default {
    
    
  namespaced: true,
  state: {
    
    
    tokenInfo: Cookies.get('yishi-token'),
  },
  mutations: {
    
    
    setTokenInfo(state, data) {
    
    
      state.tokenInfo = data
    }
  },
  actions: {
    
    },
  getters: {
    
    

  }
}

app.vue file:

 created() {
    
    
    // 浏览器打开新的tab页,登录其他用户,当前用户强制退出
    document.addEventListener('visibilitychange', function () {
    
    
      if (store.state.token.tokenInfo != Cookies.get('yi-token')) {
    
    
        router.push({
    
     name: 'login' })
      }
    })
  }

Guess you like

Origin blog.csdn.net/weixin_44834981/article/details/127421933