vue怎么实现登录跳转
Vue 实现登录跳转的方法
使用 Vue Router 导航守卫
在 router/index.js 中配置全局前置守卫,检查用户是否登录。未登录时重定向到登录页。
import Vue from 'vue'
import Router from 'vue-router'
Vue.use(Router)
const router = new Router({
routes: [
{ path: '/login', component: Login },
{ path: '/dashboard', component: Dashboard, meta: { requiresAuth: true } }
]
})
router.beforeEach((to, from, next) => {
if (to.matched.some(record => record.meta.requiresAuth)) {
const isAuthenticated = localStorage.getItem('token')
if (!isAuthenticated) {
next('/login')
} else {
next()
}
} else {
next()
}
})
登录成功后编程式导航
在登录组件的提交方法中,验证成功后使用 this.$router.push 跳转。

methods: {
handleSubmit() {
axios.post('/api/login', this.formData)
.then(response => {
localStorage.setItem('token', response.data.token)
this.$router.push('/dashboard')
})
.catch(error => {
console.error(error)
})
}
}
使用路由元信息
为需要认证的路由添加 meta 字段标记,配合导航守卫使用。

{
path: '/profile',
component: Profile,
meta: { requiresAuth: true }
}
登录状态管理
结合 Vuex 管理登录状态,使登录状态全局可用。
// store/index.js
export default new Vuex.Store({
state: {
isLoggedIn: false,
user: null
},
mutations: {
loginSuccess(state, user) {
state.isLoggedIn = true
state.user = user
},
logout(state) {
state.isLoggedIn = false
state.user = null
}
}
})
路由懒加载优化
对于需要登录后才能访问的页面,可以使用路由懒加载。
{
path: '/admin',
component: () => import('./views/Admin.vue'),
meta: { requiresAuth: true }
}
以上方法可以单独使用或组合使用,根据项目需求选择最适合的方案。全局前置守卫适合处理通用认证逻辑,编程式导航则适合处理特定场景的跳转需求。






