vue router实现登录
Vue Router 实现登录功能
在 Vue.js 项目中,使用 Vue Router 实现登录功能通常涉及路由守卫、状态管理和权限控制。以下是具体实现方法:
安装依赖
确保项目中已安装 vue-router 和状态管理库(如 vuex 或 pinia)。
npm install vue-router pinia
路由配置
在 router/index.js 中配置路由,标记需要认证的路由。
import { createRouter, createWebHistory } from 'vue-router'
const routes = [
{
path: '/login',
name: 'Login',
component: () => import('@/views/Login.vue')
},
{
path: '/dashboard',
name: 'Dashboard',
component: () => import('@/views/Dashboard.vue'),
meta: { requiresAuth: true }
}
]
const router = createRouter({
history: createWebHistory(),
routes
})
状态管理 使用 Pinia 存储用户认证状态。

// stores/auth.js
import { defineStore } from 'pinia'
export const useAuthStore = defineStore('auth', {
state: () => ({
isAuthenticated: false,
user: null
}),
actions: {
login(userData) {
this.isAuthenticated = true
this.user = userData
},
logout() {
this.isAuthenticated = false
this.user = null
}
}
})
路由守卫 实现全局前置守卫检查认证状态。
router.beforeEach((to, from, next) => {
const authStore = useAuthStore()
const requiresAuth = to.matched.some(record => record.meta.requiresAuth)
if (requiresAuth && !authStore.isAuthenticated) {
next('/login')
} else if (to.path === '/login' && authStore.isAuthenticated) {
next('/dashboard')
} else {
next()
}
})
登录组件 创建登录页面处理用户凭证。

<template>
<form @submit.prevent="handleLogin">
<input v-model="form.email" type="email" placeholder="Email">
<input v-model="form.password" type="password" placeholder="Password">
<button type="submit">Login</button>
</form>
</template>
<script setup>
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { useAuthStore } from '@/stores/auth'
const router = useRouter()
const authStore = useAuthStore()
const form = ref({
email: '',
password: ''
})
const handleLogin = async () => {
try {
await authStore.login(form.value)
router.push('/dashboard')
} catch (error) {
console.error('Login failed:', error)
}
}
</script>
API 集成 在实际项目中,需要将登录请求发送到后端 API。
actions: {
async login(credentials) {
const response = await axios.post('/api/login', credentials)
this.isAuthenticated = true
this.user = response.data.user
}
}
退出登录 实现注销功能并重定向。
const handleLogout = () => {
authStore.logout()
router.push('/login')
}
持久化登录状态 使用 localStorage 或 cookie 保持登录状态。
// 登录成功后
localStorage.setItem('token', response.data.token)
// 初始化时检查
if (localStorage.getItem('token')) {
this.isAuthenticated = true
}
这些步骤展示了 Vue Router 实现登录功能的核心流程,可以根据具体需求进行调整和扩展。






