vue登录验证怎么实现
Vue 登录验证的实现方法
前端表单验证
使用 Vue 的表单验证库如 VeeValidate 或 Element UI 的表单验证功能,确保用户输入符合要求。
安装 VeeValidate:
npm install vee-validate
在 Vue 组件中使用:
import { Form, Field, ErrorMessage } from 'vee-validate';
import * as yup from 'yup';
export default {
components: {
Form,
Field,
ErrorMessage,
},
data() {
return {
schema: yup.object({
email: yup.string().required().email(),
password: yup.string().required().min(8),
}),
};
},
};
模板部分:
<Form :validation-schema="schema" @submit="handleSubmit">
<Field name="email" type="email" />
<ErrorMessage name="email" />
<Field name="password" type="password" />
<ErrorMessage name="password" />
<button type="submit">登录</button>
</Form>
后端 API 验证
前端验证通过后,发送请求到后端 API 进行身份验证。
使用 axios 发送登录请求:
methods: {
async handleSubmit(values) {
try {
const response = await axios.post('/api/login', values);
localStorage.setItem('token', response.data.token);
this.$router.push('/dashboard');
} catch (error) {
console.error('登录失败:', error.response.data.message);
}
},
},
路由守卫
在 Vue Router 中设置全局前置守卫,保护需要认证的路由。
router.beforeEach((to, from, next) => {
const isAuthenticated = localStorage.getItem('token');
if (to.meta.requiresAuth && !isAuthenticated) {
next('/login');
} else {
next();
}
});
Token 存储与验证
登录成功后存储 token,并在每次请求时携带。
axios 拦截器设置:
axios.interceptors.request.use((config) => {
const token = localStorage.getItem('token');
if (token) {
config.headers.Authorization = `Bearer ${token}`;
}
return config;
});
错误处理
捕获并显示后端返回的验证错误。
catch (error) {
if (error.response.status === 401) {
this.errorMessage = '用户名或密码错误';
} else {
this.errorMessage = '登录失败,请稍后重试';
}
}
安全注意事项
避免在前端存储敏感信息,使用 HTTPS 传输数据,设置合理的 token 过期时间,实现刷新 token 机制。







