vue实现登录判断
Vue实现登录判断的方法
在Vue中实现登录判断通常涉及以下几个关键步骤:
使用路由守卫进行全局拦截
在Vue Router中配置全局前置守卫,检查用户登录状态:
router.beforeEach((to, from, next) => {
const isAuthenticated = localStorage.getItem('token') // 检查本地存储的token
if (to.meta.requiresAuth && !isAuthenticated) {
next('/login') // 跳转到登录页
} else {
next() // 继续导航
}
})
在路由配置中添加元信息
定义哪些路由需要登录验证:
const routes = [
{
path: '/dashboard',
component: Dashboard,
meta: { requiresAuth: true }
},
{
path: '/login',
component: Login
}
]
使用Vuex管理登录状态
在store中维护用户登录状态:
const store = new Vuex.Store({
state: {
isLoggedIn: false,
user: null
},
mutations: {
login(state, user) {
state.isLoggedIn = true
state.user = user
},
logout(state) {
state.isLoggedIn = false
state.user = null
}
}
})
在登录组件中处理认证
登录成功后更新状态:
methods: {
async login() {
try {
const response = await authService.login(this.username, this.password)
this.$store.commit('login', response.user)
localStorage.setItem('token', response.token)
this.$router.push('/dashboard')
} catch (error) {
console.error('Login failed', error)
}
}
}
在组件中使用计算属性检查登录状态
在需要登录验证的组件中添加:
computed: {
isAuthenticated() {
return this.$store.state.isLoggedIn
}
}
实现注销功能
清除登录状态和本地存储:
methods: {
logout() {
this.$store.commit('logout')
localStorage.removeItem('token')
this.$router.push('/login')
}
}
使用axios拦截器添加认证头
为API请求自动添加认证token:

axios.interceptors.request.use(config => {
const token = localStorage.getItem('token')
if (token) {
config.headers.Authorization = `Bearer ${token}`
}
return config
})
以上方法组合使用可以构建完整的登录验证系统,确保只有认证用户才能访问受保护的路由和资源。






