为管理页添加路由守卫

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,22 +17,24 @@ function userLogout() {
<template>
<div class="user-info">
<el-button type="primary" size="small"
@click="router.push('/index')"
v-if="admin">
回到用户端
<el-icon style="margin-left: 5px">
<Right/>
</el-icon>
</el-button>
<el-button type="danger" size="small"
@click="router.push('/admin')"
v-else>
前往管理端
<el-icon style="margin-left: 5px">
<Right/>
</el-icon>
</el-button>
<template v-if="store.isAdmin">
<el-button type="primary" size="small"
@click="router.push('/index')"
v-if="admin">
回到用户端
<el-icon style="margin-left: 5px">
<Right/>
</el-icon>
</el-button>
<el-button type="danger" size="small"
@click="router.push('/admin')"
v-else>
前往管理端
<el-icon style="margin-left: 5px">
<Right/>
</el-icon>
</el-button>
</template>
<template/>
<div class="profile">
<div>{{ store.user.username }}</div>

View File

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