晚上路由守护,在router.js

This commit is contained in:
jiayuqi7813
2022-06-29 23:43:22 +08:00
parent bd76fea1ec
commit 2c9b4a7f4f
6 changed files with 47 additions and 18 deletions

View File

@@ -1,4 +1,5 @@
import { createRouter, createWebHistory } from 'vue-router'
import {ElNotification} from "element-plus";
import home from "../views/Home.vue";
import Login from '../views/Login.vue'
import Challenge from '../views/Challenges.vue'
@@ -29,6 +30,9 @@ const router = createRouter({
path:'/challenges',
name:'Challenges',
component: Challenge,
meta: {
requireAuth: true,
}
},
{
path:'/scoreboard',
@@ -45,6 +49,9 @@ const router = createRouter({
path:'/users',
name:'users',
component: users,
meta: {
requireAuth: true,
}
},
{
path:'/admin',
@@ -62,4 +69,25 @@ const router = createRouter({
}
]
})
//路由守护,防止非登录用户访问至题目页面
router.beforeEach((to, from, next) => {
if (to.matched.some(record => record.meta.requireAuth)) {
if (localStorage.getItem('token')) {
next()
} else {
ElNotification.error({
title: 'Error',
message: '请先登录'
})
next({
path: '/login',
query: { redirect: to.fullPath }
})
}
} else {
next()
}
}
)
export default router