vue实现登录功能逻辑
登录功能实现逻辑
Vue实现登录功能通常涉及前端页面交互、表单验证、API请求、状态管理及路由跳转等环节。以下是核心实现逻辑:
登录表单设计
创建包含用户名和密码输入框的组件,使用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>
表单验证处理
使用Vuelidate或手动验证确保输入合法性:
// 手动验证示例
methods: {
validateForm() {
if (!this.form.username.trim()) {
alert('用户名不能为空');
return false;
}
if (this.form.password.length < 6) {
alert('密码长度需大于6位');
return false;
}
return true;
}
}
发起登录请求
通过axios发送POST请求到后端接口:
methods: {
async handleLogin() {
if (!this.validateForm()) return;
try {
const res = await axios.post('/api/login', this.form);
localStorage.setItem('token', res.data.token);
this.$router.push('/dashboard');
} catch (error) {
alert(error.response.data.message);
}
}
}
状态管理集成
使用Vuex存储登录状态和用户信息:
// store.js
actions: {
async login({ commit }, credentials) {
const res = await axios.post('/api/login', credentials);
commit('SET_USER', res.data.user);
commit('SET_TOKEN', res.data.token);
}
}
路由守卫配置
通过全局前置守卫保护需要认证的路由:
// router.js
router.beforeEach((to, from, next) => {
const isAuthenticated = localStorage.getItem('token');
if (to.meta.requiresAuth && !isAuthenticated) {
next('/login');
} else {
next();
}
});
持久化登录状态
在应用初始化时检查本地存储的token:
// main.js
const token = localStorage.getItem('token');
if (token) {
axios.defaults.headers.common['Authorization'] = `Bearer ${token}`;
store.dispatch('fetchUserInfo');
}
错误处理优化
添加网络错误和异常状态码处理:
// 在axios拦截器中统一处理
axios.interceptors.response.use(
response => response,
error => {
if (error.response.status === 401) {
localStorage.removeItem('token');
router.push('/login');
}
return Promise.reject(error);
}
);
安全注意事项
- 使用HTTPS协议传输敏感数据
- 密码字段需在前端进行基础过滤
- 设置合理的token过期时间
- 实现CSRF防护机制
- 敏感操作需进行二次验证
以上实现可根据具体项目需求进行调整,建议结合后端返回的标准化错误码进行更精细的错误处理。







