vue实现登录登出
Vue 实现登录登出功能
安装依赖
确保项目已安装 Vue 和 Vue Router。若未安装,可通过以下命令安装:
npm install vue vue-router
创建路由配置
在 src/router/index.js 中配置登录和主页路由:
import { createRouter, createWebHistory } from 'vue-router'
import Login from '../views/Login.vue'
import Home from '../views/Home.vue'
const routes = [
{ path: '/login', component: Login },
{ path: '/', component: Home, meta: { requiresAuth: true } }
]
const router = createRouter({
history: createWebHistory(),
routes
})
export default router
实现登录页面
在 src/views/Login.vue 中创建登录表单:

<template>
<form @submit.prevent="handleLogin">
<input v-model="username" placeholder="Username" />
<input v-model="password" type="password" placeholder="Password" />
<button type="submit">Login</button>
</form>
</template>
<script>
export default {
data() {
return {
username: '',
password: ''
}
},
methods: {
handleLogin() {
// 模拟登录成功
localStorage.setItem('isAuthenticated', 'true')
this.$router.push('/')
}
}
}
</script>
实现导航守卫
在 src/router/index.js 中添加全局前置守卫:
router.beforeEach((to, from, next) => {
const isAuthenticated = localStorage.getItem('isAuthenticated')
if (to.meta.requiresAuth && !isAuthenticated) {
next('/login')
} else {
next()
}
})
实现登出功能
在 src/views/Home.vue 中添加登出按钮:

<template>
<div>
<h1>Welcome</h1>
<button @click="handleLogout">Logout</button>
</div>
</template>
<script>
export default {
methods: {
handleLogout() {
localStorage.removeItem('isAuthenticated')
this.$router.push('/login')
}
}
}
</script>
状态管理(可选)
对于复杂应用,建议使用 Vuex 或 Pinia 管理登录状态:
// 使用 Pinia 示例
import { defineStore } from 'pinia'
export const useAuthStore = defineStore('auth', {
state: () => ({
isAuthenticated: false
}),
actions: {
login() {
this.isAuthenticated = true
},
logout() {
this.isAuthenticated = false
}
}
})
集成 API 调用
实际项目中需替换模拟登录为真实 API 调用:
methods: {
async handleLogin() {
try {
const response = await axios.post('/api/login', {
username: this.username,
password: this.password
})
localStorage.setItem('token', response.data.token)
this.$router.push('/')
} catch (error) {
console.error('Login failed', error)
}
}
}
安全注意事项
- 使用 HTTPS 协议传输敏感数据
- 服务端应实现 CSRF 防护
- 密码等敏感信息不应明文存储在客户端
- 考虑使用 HttpOnly 的 Cookie 存储 token
以上实现提供了完整的登录登出流程,可根据实际需求调整验证方式和状态管理策略。






