vue单页面实现登录
实现登录功能的核心步骤
创建登录组件
在Vue项目中新建一个Login.vue文件,包含表单元素(用户名/密码输入框、提交按钮)。使用v-model双向绑定数据:
<template>
<form @submit.prevent="handleLogin">
<input v-model="form.username" type="text" placeholder="用户名">
<input v-model="form.password" type="password" placeholder="密码">
<button type="submit">登录</button>
</form>
</template>
<script>
export default {
data() {
return {
form: {
username: '',
password: ''
}
}
}
}
</script>
配置路由拦截
在router/index.js中设置路由守卫,通过meta字段标记需要认证的路由:
const routes = [
{
path: '/login',
component: () => import('@/views/Login.vue')
},
{
path: '/dashboard',
component: () => import('@/views/Dashboard.vue'),
meta: { requiresAuth: true }
}
]
router.beforeEach((to, from, next) => {
const isAuthenticated = localStorage.getItem('token')
if (to.matched.some(record => record.meta.requiresAuth) && !isAuthenticated) {
next('/login')
} else {
next()
}
})
处理登录请求 在Login组件中实现提交逻辑,使用axios发送请求并存储token:
methods: {
async handleLogin() {
try {
const res = await axios.post('/api/login', this.form)
localStorage.setItem('token', res.data.token)
this.$router.push('/dashboard')
} catch (error) {
alert('登录失败')
}
}
}
状态管理方案(可选)
对于复杂应用,建议使用Vuex集中管理登录状态:

// store/modules/auth.js
const actions = {
login({ commit }, credentials) {
return axios.post('/api/login', credentials)
.then(res => {
commit('SET_TOKEN', res.data.token)
localStorage.setItem('token', res.data.token)
})
}
}
安全增强措施
- 使用HTTPS传输数据
- 前端应对密码进行基本校验(如最小长度)
- 后端返回的token应设置合理有效期
- 考虑实现refresh token机制
- 敏感路由跳转时清除表单数据
界面反馈优化
- 添加加载状态指示器
- 显示表单验证错误信息
- 登录成功后显示Toast通知
- 实现"记住我"功能(需配合后端设置长期token)
以上实现可根据具体项目需求调整,核心要点是正确处理认证状态、路由守卫和token存储。对于生产环境,建议增加CSRF防护等安全措施。






