vue登录业务的实现
登录业务实现步骤
1. 创建登录表单组件
使用Vue的单文件组件(SFC)结构,结合<template>、<script>和<style>实现表单UI。
<template>
<form @submit.prevent="handleSubmit">
<input v-model="form.username" placeholder="用户名" />
<input v-model="form.password" type="password" placeholder="密码" />
<button type="submit">登录</button>
</form>
</template>
<script>
export default {
data() {
return {
form: {
username: '',
password: ''
}
}
}
}
</script>
2. 表单验证
通过计算属性或第三方库(如VeeValidate)校验输入。

computed: {
isValid() {
return this.form.username.length > 0 && this.form.password.length >= 6
}
}
3. 提交逻辑与API调用
使用Axios或Fetch发送登录请求,处理响应结果。

methods: {
async handleSubmit() {
if (!this.isValid) return
try {
const res = await axios.post('/api/login', this.form)
localStorage.setItem('token', res.data.token)
this.$router.push('/dashboard')
} catch (error) {
console.error('登录失败:', error)
}
}
}
4. 状态管理(可选)
若项目使用Vuex或Pinia,可将用户状态存入全局Store。
// Pinia示例
import { useAuthStore } from '@/stores/auth'
const authStore = useAuthStore()
authStore.login(res.data.user)
5. 路由守卫
通过Vue Router的导航守卫保护需认证的路由。
router.beforeEach((to) => {
if (to.meta.requiresAuth && !localStorage.getItem('token')) {
return '/login'
}
})
关键注意事项
- 安全性:密码传输需HTTPS,服务端应哈希存储密码。
- Token管理:建议使用HttpOnly Cookie或Secure LocalStorage存储令牌。
- 错误反馈:前端需展示服务端返回的错误信息(如“用户名不存在”)。
扩展功能
- 添加“记住我”选项,延长Token有效期。
- 集成第三方登录(OAuth2.0)。
- 实现登录加载状态与按钮防重提交。






