vue如何实现登录拦截
Vue 实现登录拦截的方法
使用路由守卫(Route Guards)
在 Vue 中,可以通过路由守卫(beforeEach)实现登录拦截。路由守卫会在路由跳转前执行,用于检查用户是否已登录。
// router/index.js
import router from './router'
import store from './store'
router.beforeEach((to, from, next) => {
const isAuthenticated = store.getters.isAuthenticated
if (to.matched.some(record => record.meta.requiresAuth)) {
if (!isAuthenticated) {
next({
path: '/login',
query: { redirect: to.fullPath }
})
} else {
next()
}
} else {
next()
}
})
定义路由元信息
在路由配置中,可以通过 meta 字段标记哪些路由需要登录权限。

// router/index.js
const routes = [
{
path: '/dashboard',
component: Dashboard,
meta: { requiresAuth: true }
},
{
path: '/login',
component: Login
}
]
结合 Vuex 管理登录状态
使用 Vuex 存储和管理用户的登录状态,确保全局可访问。
// store/index.js
const store = new Vuex.Store({
state: {
isAuthenticated: false,
user: null
},
mutations: {
setAuth(state, payload) {
state.isAuthenticated = payload.isAuthenticated
state.user = payload.user
}
},
getters: {
isAuthenticated: state => state.isAuthenticated
}
})
登录逻辑实现
在登录组件中,调用登录接口并更新 Vuex 状态,成功后跳转到目标页面。

// Login.vue
methods: {
async login() {
try {
const response = await authService.login(this.form)
this.$store.commit('setAuth', {
isAuthenticated: true,
user: response.user
})
const redirect = this.$route.query.redirect || '/'
this.$router.push(redirect)
} catch (error) {
console.error('Login failed:', error)
}
}
}
退出登录处理
在退出登录时,清除 Vuex 中的状态并跳转到登录页。
// Logout.vue
methods: {
logout() {
this.$store.commit('setAuth', {
isAuthenticated: false,
user: null
})
this.$router.push('/login')
}
}
使用导航守卫检查 Token
如果使用 Token 验证,可以在路由守卫中检查 Token 是否有效。
router.beforeEach((to, from, next) => {
const token = localStorage.getItem('token')
if (to.matched.some(record => record.meta.requiresAuth)) {
if (!token) {
next('/login')
} else {
// 验证 Token 有效性
verifyToken(token).then(isValid => {
if (isValid) {
next()
} else {
next('/login')
}
})
}
} else {
next()
}
})
通过以上方法,可以灵活实现 Vue 中的登录拦截功能,确保未登录用户无法访问受保护的路由。






