token

HTTP: stateless cookie: [client] record state session: [server] Record state token: maintain state ———— exist [cross-domain]

Route navigation guard

If the user is not logged in, but accesses a specific page using a URL, you need to navigate to the login page again.

The login

1. Define routes. 2. Hang the route navigation guard before exposing routes

To The path routing object to be accessed (including so, params, meta, etc.)fromNext is a function that says pass next() pass next('/login') Forced jumpCopy the code
// 2. Mount the route navigator
router.beforeEach((to, from, next) = > {
  // 
  if (to.path === '/login') return next()
  // else if (to.path === '/home') return next()

  / / access token
  const tokenStr = window.sessionStorage.getItem('token')
  if(! tokenStr)return next('/login')
  next()
})
Copy the code

exit

Log out button binding events. The window. The sessionStorage. The clear () / / clear the sessionStorage token $router. Push (‘/login ‘) / / routing is redirected to the login page

async logout() {
      const confirmed = await this.$confirm('Are you sure you want to log out? '.'tip', {
        confirmButtonText: 'sure'.cancelButtonText: 'cancel'.type: 'warning'
      }).catch(err= > {
        return err
      })
      if(confirmed ! = ='confirm') {
        return
      }
      const { data: res } = await this.$http.post('user/logout')
      if (res.code === 200) {
        this.$message.success('Logged out')
        window.sessionStorage.clear() // Clear tokens in sessionStorage
      }
      this.$router.push('/login')}Copy the code