vue3导航守卫用户教师管理员分权案例
以下是一个使用 Vue3 导航守卫实现用户、教师和管理员分权的案例:
// main.js
import { createApp } from 'vue'
import { createRouter, createWebHistory } from 'vue-router'
import App from './App.vue'
const router = createRouter({
history: createWebHistory(),
routes: [
{
path: '/',
name: 'Home',
component: Home,
meta: {
requiresAuth: true,
roles: ['user', 'teacher', 'admin']
}
},
{
path: '/user',
name: 'UserDashboard',
component: UserDashboard,
meta: {
requiresAuth: true,
roles: ['user']
}
},
{
path: '/teacher',
name: 'TeacherDashboard',
component: TeacherDashboard,
meta: {
requiresAuth: true,
roles: ['teacher', 'admin']
}
},
{
path: '/admin',
name: 'AdminDashboard',
component: AdminDashboard,
meta: {
requiresAuth: true,
roles: ['admin']
}
},
{
path: '/login',
name: 'Login',
component: Login
}
]
})
router.beforeEach((to, from, next) => {
const isAuthenticated = // 检查用户是否已经登录
const userRole = // 获取当前用户角色
// 检查路由是否需要身份验证
if (to.meta.requiresAuth) {
// 检查用户是否已经登录
if (!isAuthenticated) {
// 如果用户未登录,重定向到登录页面
next('/login')
} else {
// 检查用户角色是否具备访问该路由的权限
if (to.meta.roles.includes(userRole)) {
next()
} else {
// 如果用户角色不具备访问权限,重定向到首页或其他页面
next('/')
}
}
} else {
next()
}
})
createApp(App).use(router).mount('#app')
在上述代码中,我们定义了四个路由:Home、UserDashboard、TeacherDashboard 和 AdminDashboard。每个路由都有一个 meta 对象,其中包含 requiresAuth 和 roles 属性。requiresAuth 表示该路由是否需要身份验证,roles 表示有权限访问该路由的角色列表。
在 beforeEach 导航守卫中,我们首先检查用户是否已经登录,并获取当前用户的角色。然后,我们根据路由的 meta 对象进行权限验证。如果用户未登录,则重定向到登录页面。如果用户已登录,但角色不具备访问权限,则重定向到首页或其他页面。
这样,我们就实现了用户、教师和管理员分权的导航守卫案例。请注意,这只是一个简单的示例,实际项目中可能需要更复杂的权限管理逻辑
原文地址: https://www.cveoy.top/t/topic/h4BM 著作权归作者所有。请勿转载和采集!