vue 实现登录跳转
实现登录跳转的核心逻辑
在Vue中实现登录跳转通常涉及路由守卫、状态管理和API交互。以下是具体实现方式:
配置路由守卫
在路由配置文件中添加beforeEach守卫,检查用户是否已登录。未登录时重定向到登录页:
// router/index.js
import Vue from 'vue'
import Router from 'vue-router'
import store from '@/store'
Vue.use(Router)
const router = new Router({
routes: [...]
})
router.beforeEach((to, from, next) => {
const isAuthenticated = store.getters.isAuthenticated
if (to.matched.some(record => record.meta.requiresAuth) && !isAuthenticated) {
next('/login')
} else {
next()
}
})
创建登录组件
构建包含表单提交逻辑的登录组件,成功登录后跳转到目标页面:
<template>
<form @submit.prevent="handleLogin">
<input v-model="username" type="text" placeholder="Username">
<input v-model="password" type="password" placeholder="Password">
<button type="submit">Login</button>
</form>
</template>
<script>
export default {
data() {
return {
username: '',
password: ''
}
},
methods: {
async handleLogin() {
try {
await this.$store.dispatch('login', {
username: this.username,
password: this.password
})
this.$router.push(this.$route.query.redirect || '/dashboard')
} catch (error) {
alert('Login failed')
}
}
}
}
</script>
设置Vuex状态管理
通过Vuex存储登录状态和用户信息:
// store/index.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
user: null,
token: null
},
getters: {
isAuthenticated: state => !!state.token
},
mutations: {
SET_USER(state, { user, token }) {
state.user = user
state.token = token
}
},
actions: {
async login({ commit }, credentials) {
const response = await api.post('/login', credentials)
commit('SET_USER', response.data)
}
}
})
处理带重定向的登录链接
在需要登录的页面跳转时,携带原始路径参数:
// 在需要权限的组件中
this.$router.push({
path: '/login',
query: { redirect: this.$route.fullPath }
})
持久化登录状态
使用localStorage或cookie保持登录状态:
// 在Vuex mutations中添加持久化逻辑
mutations: {
SET_USER(state, { user, token }) {
state.user = user
state.token = token
localStorage.setItem('authToken', token)
},
INIT_STATE(state) {
state.token = localStorage.getItem('authToken')
}
}
// 在应用初始化时调用
store.commit('INIT_STATE')
实现注销功能
清除状态并重定向到登录页:
methods: {
logout() {
this.$store.commit('SET_USER', { user: null, token: null })
localStorage.removeItem('authToken')
this.$router.push('/login')
}
}






