vue会话实现
Vue 会话实现方法
使用 Vuex 管理会话状态
安装 Vuex 并创建 store 模块管理用户会话状态。定义一个包含用户信息和登录状态的 state,通过 mutations 和 actions 更新状态。
// store/modules/auth.js
const state = {
user: null,
isAuthenticated: false
}
const mutations = {
SET_USER(state, user) {
state.user = user
state.isAuthenticated = !!user
}
}
const actions = {
login({ commit }, credentials) {
return authService.login(credentials).then(user => {
commit('SET_USER', user)
})
},
logout({ commit }) {
return authService.logout().then(() => {
commit('SET_USER', null)
})
}
}
实现登录组件
创建登录组件处理用户凭证提交。使用 v-model 绑定表单输入,调用 Vuex action 进行认证。
<template>
<form @submit.prevent="handleSubmit">
<input v-model="email" type="email" placeholder="Email">
<input v-model="password" type="password" placeholder="Password">
<button type="submit">Login</button>
</form>
</template>
<script>
export default {
data() {
return {
email: '',
password: ''
}
},
methods: {
handleSubmit() {
this.$store.dispatch('auth/login', {
email: this.email,
password: this.password
}).then(() => {
this.$router.push('/dashboard')
})
}
}
}
</script>
路由守卫保护页面
配置路由守卫检查认证状态,限制未授权访问。在 router.beforeEach 钩子中验证 Vuex 的 isAuthenticated 状态。
// router/index.js
router.beforeEach((to, from, next) => {
const requiresAuth = to.matched.some(record => record.meta.requiresAuth)
const isAuthenticated = store.getters['auth/isAuthenticated']
if (requiresAuth && !isAuthenticated) {
next('/login')
} else {
next()
}
})
持久化会话状态
使用 localStorage 或 cookie 持久化会话。登录成功后存储 token,初始化时检查存储恢复状态。
// authService.js
export default {
login(credentials) {
return api.post('/login', credentials).then(response => {
localStorage.setItem('token', response.data.token)
return response.data.user
})
},
checkAuth() {
const token = localStorage.getItem('token')
if (token) {
return api.get('/user').then(response => response.data)
}
return Promise.resolve(null)
}
}
全局状态访问
创建全局 mixin 或使用计算属性方便组件访问会话状态。通过 mapState 或 mapGetters 简化状态访问。
// mixins/auth.js
export default {
computed: {
...mapState('auth', ['user', 'isAuthenticated'])
}
}
错误处理和加载状态
添加加载状态和错误提示改善用户体验。在组件中处理异步操作的状态和可能的错误。
data() {
return {
isLoading: false,
error: null
}
},
methods: {
async handleSubmit() {
this.isLoading = true
this.error = null
try {
await this.$store.dispatch('auth/login', credentials)
this.$router.push('/dashboard')
} catch (error) {
this.error = error.response.data.message
} finally {
this.isLoading = false
}
}
}






