用vue实现自动登录
实现自动登录的基本思路
自动登录通常通过结合前端(Vue)和后端(如Token验证)实现。核心逻辑是用户首次登录时,后端返回Token并存储在前端(如localStorage),下次打开应用时自动携带Token验证。
前端存储Token
登录成功后,将后端返回的Token存储到localStorage或sessionStorage:

// 登录成功后的回调
localStorage.setItem('authToken', response.data.token);
路由守卫验证Token
在Vue Router的全局前置守卫中检查Token,决定是否跳转登录页:

router.beforeEach((to, from, next) => {
const token = localStorage.getItem('authToken');
if (to.meta.requiresAuth && !token) {
next('/login');
} else {
next();
}
});
自动发送Token的Axios拦截器
通过Axios请求拦截器,自动在请求头中添加Token:
axios.interceptors.request.use(config => {
const token = localStorage.getItem('authToken');
if (token) {
config.headers.Authorization = `Bearer ${token}`;
}
return config;
});
后端Token验证逻辑
后端需提供验证接口(如/auth/validate),前端在初始化时调用:
created() {
if (localStorage.getItem('authToken')) {
axios.get('/auth/validate').catch(() => {
localStorage.removeItem('authToken');
});
}
}
安全注意事项
- 使用
httpOnly的Cookie存储Token可增强安全性(需后端配合)。 - 敏感操作应要求重新输入密码。
- Token应设置合理过期时间,通过Refresh Token机制续期。
完整示例代码
// main.js
axios.interceptors.request.use(config => {
const token = localStorage.getItem('authToken');
if (token) config.headers.Authorization = `Bearer ${token}`;
return config;
});
router.beforeEach((to, from, next) => {
const isAuthenticated = localStorage.getItem('authToken');
if (to.meta.requiresAuth && !isAuthenticated) {
next('/login');
} else {
next();
}
});
// Login.vue
methods: {
login() {
axios.post('/login', this.credentials).then(res => {
localStorage.setItem('authToken', res.data.token);
this.$router.push('/dashboard');
});
}
}
通过以上步骤可实现基础自动登录功能,实际项目中需根据具体需求调整安全策略和用户体验设计。






