为管理页添加路由守卫

This commit is contained in:
柏码の讲师 2024-12-23 17:56:19 +08:00
parent b03e32f169
commit aea61ec3c4
2 changed files with 23 additions and 17 deletions

View File

@ -17,6 +17,7 @@ function userLogout() {
<template> <template>
<div class="user-info"> <div class="user-info">
<template v-if="store.isAdmin">
<el-button type="primary" size="small" <el-button type="primary" size="small"
@click="router.push('/index')" @click="router.push('/index')"
v-if="admin"> v-if="admin">
@ -33,6 +34,7 @@ function userLogout() {
<Right/> <Right/>
</el-icon> </el-icon>
</el-button> </el-button>
</template>
<template/> <template/>
<div class="profile"> <div class="profile">
<div>{{ store.user.username }}</div> <div>{{ store.user.username }}</div>

View File

@ -1,5 +1,6 @@
import { createRouter, createWebHistory } from 'vue-router' import { createRouter, createWebHistory } from 'vue-router'
import { unauthorized } from "@/net"; import { unauthorized } from "@/net";
import {useStore} from "@/store";
const router = createRouter({ const router = createRouter({
history: createWebHistory(import.meta.env.BASE_URL), history: createWebHistory(import.meta.env.BASE_URL),
@ -65,9 +66,12 @@ const router = createRouter({
}) })
router.beforeEach((to, from, next) => { router.beforeEach((to, from, next) => {
const isUnauthorized = unauthorized() const store = useStore()
const isUnauthorized = unauthorized(), admin = store.isAdmin
if(to.name.startsWith('welcome') && !isUnauthorized) { if(to.name.startsWith('welcome') && !isUnauthorized) {
next('/index') next('/index')
} else if(to.fullPath.startsWith('/admin') && !admin) {
next('/index')
} else if(to.fullPath.startsWith('/index') && isUnauthorized) { } else if(to.fullPath.startsWith('/index') && isUnauthorized) {
next('/') next('/')
} else { } else {