在Vue 3 + TypeScript项目中实现高效的路由权限控制,通常可以通过以下几种方式来实现。以下是一个较为常见的实现方案:
首先,定义你的路由和对应的权限。你可以在路由配置中添加一个meta
字段来存储权限信息。
import { RouteRecordRaw } from 'vue-router';
const routes: Array<RouteRecordRaw> = [
{
path: '/',
name: 'Home',
component: () => import('@/views/Home.vue'),
meta: { requiresAuth: true, roles: ['admin', 'user'] }
},
{
path: '/admin',
name: 'Admin',
component: () => import('@/views/Admin.vue'),
meta: { requiresAuth: true, roles: ['admin'] }
},
{
path: '/login',
name: 'Login',
component: () => import('@/views/Login.vue'),
meta: { requiresAuth: false }
}
];
export default routes;
使用Vue Router的beforeEach
钩子来检查用户是否有权限访问某个路由。
import { createRouter, createWebHistory } from 'vue-router';
import routes from './routes';
import { useAuthStore } from '@/stores/auth'; // 假设你使用Pinia来管理用户状态
const router = createRouter({
history: createWebHistory(),
routes
});
router.beforeEach((to, from, next) => {
const authStore = useAuthStore();
const isAuthenticated = authStore.isAuthenticated;
const userRoles = authStore.userRoles;
// 检查路由是否需要认证
if (to.meta.requiresAuth && !isAuthenticated) {
// 如果未认证,重定向到登录页面
next({ name: 'Login' });
} else if (to.meta.roles) {
// 检查用户是否有访问该路由的权限
const hasPermission = to.meta.roles.some((role: string) => userRoles.includes(role));
if (hasPermission) {
next();
} else {
// 如果没有权限,重定向到首页或其他页面
next({ name: 'Home' });
}
} else {
// 如果不需要认证或权限,直接放行
next();
}
});
export default router;
使用Pinia或Vuex来管理用户状态,包括用户的认证状态和角色信息。
import { defineStore } from 'pinia';
export const useAuthStore = defineStore('auth', {
state: () => ({
isAuthenticated: false,
userRoles: [] as string[]
}),
actions: {
login(roles: string[]) {
this.isAuthenticated = true;
this.userRoles = roles;
},
logout() {
this.isAuthenticated = false;
this.userRoles = [];
}
}
});
在登录和登出时,更新用户状态。
import { useAuthStore } from '@/stores/auth';
const authStore = useAuthStore();
// 登录
authStore.login(['admin']); // 假设用户是admin角色
// 登出
authStore.logout();
如果你的路由是动态的,可以根据用户权限动态加载路由。
import { RouteRecordRaw } from 'vue-router';
import { useAuthStore } from '@/stores/auth';
const authStore = useAuthStore();
const dynamicRoutes: Array<RouteRecordRaw> = [
{
path: '/dashboard',
name: 'Dashboard',
component: () => import('@/views/Dashboard.vue'),
meta: { requiresAuth: true, roles: ['admin'] }
}
];
// 根据用户权限动态添加路由
if (authStore.userRoles.includes('admin')) {
router.addRoute(dynamicRoutes[0]);
}
最后,确保处理未找到的路由。
router.beforeEach((to, from, next) => {
if (!to.matched.length) {
next({ name: 'NotFound' }); // 假设你有一个NotFound页面
} else {
next();
}
});
通过以上步骤,你可以在Vue 3 + TypeScript项目中实现高效的路由权限控制。核心思想是利用Vue Router的beforeEach
钩子来检查用户权限,并结合状态管理工具(如Pinia或Vuex)来管理用户状态。这种方式既灵活又易于维护,适用于大多数中小型项目。