vue的路由实现登录
Vue 路由实现登录功能
路由配置
在 router/index.js 中配置登录路由和需要权限的路由。登录路由设置为公开访问,其他路由通过 meta 字段标记需要认证。
const routes = [
{
path: '/login',
name: 'Login',
component: () => import('@/views/Login.vue'),
meta: { requiresAuth: false }
},
{
path: '/dashboard',
name: 'Dashboard',
component: () => import('@/views/Dashboard.vue'),
meta: { requiresAuth: true }
}
]
路由守卫
使用全局前置守卫 beforeEach 检查路由是否需要认证。未登录用户尝试访问受保护路由时,重定向到登录页。
router.beforeEach((to, from, next) => {
const isAuthenticated = localStorage.getItem('token')
if (to.meta.requiresAuth && !isAuthenticated) {
next('/login')
} else {
next()
}
})
登录逻辑
在登录组件中处理用户认证。成功登录后存储 token 并跳转到目标页面。
methods: {
async handleLogin() {
try {
const response = await loginApi(this.form)
localStorage.setItem('token', response.data.token)
this.$router.push('/dashboard')
} catch (error) {
console.error('Login failed', error)
}
}
}
注销处理
清除本地存储的认证信息并重定向到登录页。
methods: {
handleLogout() {
localStorage.removeItem('token')
this.$router.push('/login')
}
}
动态路由
对于更复杂的权限系统,可以根据用户角色动态添加路由。
const adminRoutes = [
{
path: '/admin',
component: () => import('@/views/Admin.vue')
}
]
function addDynamicRoutes() {
const role = getUserRole()
if (role === 'admin') {
router.addRoutes(adminRoutes)
}
}






