为管理页添加路由守卫

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