Vue navigation guard implements routing control

Realize routing control, users who have not logged in cannot access other pages through the address, and will be redirected back to the login interface.

import Vue from 'vue'
import Router from 'vue-router'
import {getCookie} from "@/assets/js/cookie";  //从cookie中判断是否登录了

Vue.use(Router)
  const routes = [
    {
      path: '/',
      name: 'Login',
      component: () => import('@/views/login/login')
    },
    {
      path: '/main',
      name: 'Main',
      component: () => import('@/views/main/main.vue')
    },
    {
      path: '/home',
      name: 'Home',
      component: () => import('@/views/home/home.vue')
    }
  ]

const router = new Router({
  mode: 'history',
  routes
})
export default router

router.beforeEach(async (to, from,next) => {
  if (getCookie("username") === ""   //判断是否已经登录了
      && to.name !== 'Login'       //判断是否要去的页面已经是登录页面了,避免反复跳转
  ) 
    next({ name: 'Login' })
  else next()
})

Guess you like

Origin blog.csdn.net/qq_45878280/article/details/127347048