VUE学习笔记(十六)-全局守卫
全局守卫
src/router/index.js
import { createRouter, createWebHistory } from "vue-router"; import HomeView from "../views/HomeView.vue"; import { getToken, isTokenFromLocalStorageVaild } from "@/auth/auth.service"; const routes = [ { path: "/login", name: "login", component: () => import("@/auth/views/UserLogin.vue"), }, { path: "/", name: "/", component: () => import("@/views/LayoutView.vue"), redirect: "/home", children: [ { path: "/", name: "home", component: HomeView, }, { path: "/about", name: "about", // route level code-splitting // this generates a separate chunk (about.[hash].js) for this route // which is lazy-loaded when the route is visited. component: () => import(/* webpackChunkName: "about" */ "../views/AboutView.vue"), }, { path: "/category", name: "category", component: () => import(/* webpackChunkName: "about" */ "../views/CategoryView.vue"), }, { path: "/addCategory", name: "addCategory", component: () => import("../components/AddCategory.vue"), }, ], }, ]; const router = createRouter({ history: createWebHistory(process.env.BASE_URL), routes, }); //全局守卫(前置、后置)、独享守卫、组件内守卫 router.beforeEach((to, from, next) => { //to:可以获取到目的地的路由 //from:可以获取到从哪里来的路由 //next():继续、放行(用法1--next()表示继续、2--next("/login")去哪里、3--next(false)取消当前导航) //通过token判断有没有登陆 if (getToken()) { //已登陆(就不能去登陆页了) if (to.path == "/login") { next("/"); } else { //检查token有没有过期 if (isTokenFromLocalStorageVaild()) { //未过期 next(); } else { //已过期 next("/login"); } } } else { //未登陆 if (to.path == "/login") { next(); } else { next("/login"); } } }); export default router;