2026-06-06 23:39:58
在 Vue 3 中使用路由守卫进行鉴权,可以通过全局前置守卫 beforeEach 实现。以下是详细步骤:
1. 安装 Vue Router确保已安装 Vue Router,若未安装可通过以下命令安装:
npm install vue-router@next# 或yarn add vue-router@next2. 配置路由在 src/router/index.js 中配置路由,并通过 meta 字段标记需要鉴权的路由:
import { createRouter, createWebHistory } from 'vue-router';import Home from '../views/Home.vue';import About from '../views/About.vue';import Login from '../views/Login.vue';const routes = [ { path: '/', name: 'Home', component: Home, meta: { requiresAuth: true } // 标记需要登录 }, { path: '/about', name: 'About', component: About, meta: { requiresAuth: true } }, { path: '/login', name: 'Login', component: Login }, { path: '/:pathMatch(.*)*', name: 'NotFound', component: () => import('../views/NotFound.vue') }];const router = createRouter({ history: createWebHistory(process.env.BASE_URL), routes});export default router;3. 注册路由在 main.js 或 main.ts 中注册路由:
import { createApp } from 'vue';import App from './App.vue';import router from './router';createApp(App).use(router).mount('#app');4. 创建登录页面组件在 src/views/Login.vue 中实现登录逻辑:
<template> <div class="login"> <h1>登录</h1> <form @submit.prevent="handleLogin"> <div> <label for="username">用户名:</label> <input type="text" id="username" v-model="username" required /> </div> <div> <label for="password">密码:</label> <input type="password" id="password" v-model="password" required /> </div> <button type="submit">登录</button> </form> </div></template><script>export default { data() { return { username: '', password: '' }; }, methods: { handleLogin() { // 模拟登录成功 localStorage.setItem('isAuthenticated', 'true'); this.$router.push({ name: 'Home' }); } }};</script><style scoped>.login { max-width: 400px; margin: 0 auto; padding: 20px; border: 1px solid #ccc; border-radius: 5px;}</style>5. 配置全局前置守卫在路由配置文件中添加 beforeEach 守卫,检查用户是否登录:
// router/index.jsrouter.beforeEach((to, from, next) => { const requiresAuth = to.matched.some(record => record.meta.requiresAuth); const isAuthenticated = localStorage.getItem('isAuthenticated') === 'true'; if (requiresAuth && !isAuthenticated) { next({ name: 'Login' }); // 未登录则跳转到登录页 } else { next(); // 放行 }});6. 测试启动项目,尝试访问需要登录的页面(如 / 或 /about)。若未登录,应自动跳转到 /login。登录成功后可正常访问。
7. 退出登录在需要退出登录的组件中清除认证状态:
<template> <div> <h1>退出登录</h1> <button @click="logout">退出</button> </div></template><script>export default { methods: { logout() { localStorage.removeItem('isAuthenticated'); this.$router.push({ name: 'Login' }); } }};</script>8. 总结通过以上步骤,实现了 Vue 3 中的路由鉴权功能:

如需更复杂的权限控制(如角色管理),可扩展 meta 字段(如 meta: { roles: ['admin'] })并在守卫中校验。