vue实现登录认证
Vue 登录认证实现方法
使用 Vue Router 和 Vuex 管理登录状态
在 Vue 项目中,通常使用 Vue Router 进行路由管理,Vuex 进行状态管理。登录认证的核心是验证用户身份并维护登录状态。
创建 Vuex store 模块管理用户认证状态:
// store/auth.js
const state = {
user: null,
token: null,
isAuthenticated: false
}
const mutations = {
SET_USER(state, user) {
state.user = user
state.isAuthenticated = !!user
},
SET_TOKEN(state, token) {
state.token = token
},
LOGOUT(state) {
state.user = null
state.token = null
state.isAuthenticated = false
}
}
const actions = {
login({ commit }, { user, token }) {
commit('SET_USER', user)
commit('SET_TOKEN', token)
localStorage.setItem('token', token)
},
logout({ commit }) {
commit('LOGOUT')
localStorage.removeItem('token')
}
}
export default {
namespaced: true,
state,
mutations,
actions
}
实现登录表单组件
创建登录表单组件处理用户输入和提交:
<template>
<form @submit.prevent="handleSubmit">
<input v-model="form.username" type="text" placeholder="用户名">
<input v-model="form.password" type="password" placeholder="密码">
<button type="submit">登录</button>
</form>
</template>
<script>
export default {
data() {
return {
form: {
username: '',
password: ''
}
}
},
methods: {
async handleSubmit() {
try {
const response = await axios.post('/api/auth/login', this.form)
this.$store.dispatch('auth/login', {
user: response.data.user,
token: response.data.token
})
this.$router.push('/dashboard')
} catch (error) {
console.error('登录失败:', error)
}
}
}
}
</script>
配置路由守卫
使用 Vue Router 的导航守卫保护需要认证的路由:
// router/index.js
router.beforeEach((to, from, next) => {
const isAuthenticated = store.state.auth.isAuthenticated
const requiresAuth = to.matched.some(record => record.meta.requiresAuth)
if (requiresAuth && !isAuthenticated) {
next('/login')
} else if (to.path === '/login' && isAuthenticated) {
next('/')
} else {
next()
}
})
持久化登录状态
应用启动时检查本地存储中的 token 并恢复登录状态:
// main.js
const token = localStorage.getItem('token')
if (token) {
axios.defaults.headers.common['Authorization'] = `Bearer ${token}`
store.dispatch('auth/checkAuth')
}
添加 HTTP 拦截器
配置 axios 拦截器自动添加认证 token 并处理过期情况:
// utils/axios.js
axios.interceptors.request.use(config => {
const token = store.state.auth.token
if (token) {
config.headers.Authorization = `Bearer ${token}`
}
return config
})
axios.interceptors.response.use(
response => response,
error => {
if (error.response.status === 401) {
store.dispatch('auth/logout')
router.push('/login')
}
return Promise.reject(error)
}
)
实现注销功能
创建注销按钮触发注销操作:
<template>
<button @click="logout">注销</button>
</template>
<script>
export default {
methods: {
logout() {
this.$store.dispatch('auth/logout')
this.$router.push('/login')
}
}
}
</script>
这种方法提供了完整的登录认证流程,包括状态管理、路由保护、持久化和 HTTP 请求处理。根据具体需求可以进一步扩展,如添加角色权限控制、双因素认证等功能。







