15.Vue Router 身份验证-页面拦截

This commit is contained in:
xuewuerduo 2024-07-15 21:54:19 +08:00
parent 269b6ee5a7
commit ec3bb3d04f
1 changed files with 23 additions and 2 deletions

View File

@ -1,4 +1,5 @@
import { createRouter, createWebHistory } from "vue-router" import { createRouter, createWebHistory } from "vue-router"
import {useAdminStore} from "@/stores/admin/admin.js";
const routes= [ const routes= [
{ {
path: "/login", // http://localhost:5173/login path: "/login", // http://localhost:5173/login
@ -6,8 +7,8 @@ const routes= [
}, },
{ {
path: "/admin", // http://localhost:5173/admin path: "/admin", // http://localhost:5173/admin
component: () => import("@/views/admin/home.vue") component: () => import("@/views/admin/home.vue"),
meta: { requiresAuth: true }, //身份验证
} }
] ]
@ -15,4 +16,24 @@ const router = createRouter({
history: createWebHistory(), history: createWebHistory(),
routes routes
}) })
router.beforeEach((to, from, next) => {
// console.log(to.meta.requiresAuth)
if ( to.meta.requiresAuth ){
console.log("需要身份验证")
//初始化
const adminStore = useAdminStore()
if ( adminStore.data.token === "" ){
console.log("未登录")
router.push("/login")
}
}else{
console.log("不需要身份验证")
}
next()
})
export default router export default router