vue实现登陆拦截
实现登录拦截的方法
在Vue应用中实现登录拦截通常涉及路由守卫和状态管理。以下是几种常见的方法:
使用全局前置守卫
通过router.beforeEach在路由跳转前检查用户登录状态,未登录则重定向到登录页。
// router/index.js
import router from './router'
import store from './store'
router.beforeEach((to, from, next) => {
const isAuthenticated = store.state.user.isAuthenticated
if (to.meta.requiresAuth && !isAuthenticated) {
next('/login')
} else {
next()
}
})
配置路由元信息
在路由配置中添加meta字段标记需要认证的路由。
const routes = [
{
path: '/dashboard',
component: Dashboard,
meta: { requiresAuth: true }
},
{
path: '/login',
component: Login
}
]
结合Vuex状态管理
使用Vuex存储和检查用户认证状态。
// store/modules/user.js
const state = {
isAuthenticated: false,
user: null
}
const mutations = {
SET_AUTH(state, status) {
state.isAuthenticated = status
}
}
处理Token验证
在拦截器中验证JWT等认证Token的有效性。
// axios拦截器
axios.interceptors.request.use(config => {
const token = localStorage.getItem('token')
if (token) {
config.headers.Authorization = `Bearer ${token}`
}
return config
})
axios.interceptors.response.use(
response => response,
error => {
if (error.response.status === 401) {
router.push('/login')
}
return Promise.reject(error)
}
)
登录成功处理
登录成功后更新状态并重定向。
// Login.vue methods
login() {
auth.login(this.credentials).then(response => {
localStorage.setItem('token', response.data.token)
this.$store.commit('SET_AUTH', true)
this.$router.push(this.$route.query.redirect || '/dashboard')
})
}
退出登录处理
清除认证信息并重定向到登录页。
// Logout.vue
logout() {
localStorage.removeItem('token')
this.$store.commit('SET_AUTH', false)
this.$router.push('/login')
}
注意事项
- 确保敏感路由都添加了
requiresAuth元信息 - 考虑Token过期时间的处理
- 实现刷新页面后的状态保持
- 生产环境应使用HTTPS保护认证信息
- 后端也需要相应的认证中间件进行双重保护







