Vue router.beforeEach中的next({path: '/login'}) 不跳转

想做一个路由拦截:

  1. Vuex 中有用户的状态,其中一个属性是: user
  2. user 为空时说明未登录,跳转到登录页面
  3. user 不为空时,说明已经登录,直接路由到下一个页面

代码是这样的:

  • router/index.js 文件
import Vue from 'vue'
import Router from 'vue-router'
Vue.use(Router)
export default new Router ({
    mode: 'history',
    routes: [...],
    scrollBehavior: (to, from, savedPosition) => {
        return savedPosition || {x: 0, y: 0}
    }
})
  • main.js 文件
import router from './router'

new Vue({
    router,
})

router.beforeEach((to, from, next) => {
    // 这里会持续性的输出 null
    alert(JSON.stringify(store.state.user.user)) 
    if(store.state.user.user !== null){
        next()
    }else {
        alert('用户尚未登录')
        next({
            path: '/login',
            query: {redirect: to.fullPath}
        })
    }
})

// 运行的结果是,持续性的输出:
// null
// 用户尚未登录
// 循环不断...

问题就是:

  1. 该如何解决?
  2. 什么原因造成的?
阅读 16.6k
4 个回答
if (store.state.user.user !== null || to.path === '/login') {
    next()
}

在meta中添加一个auth认证参数

{
    path: '/home',
    name: 'home',
    component: Home,
    meta: {
        auth: true,
        keep: true
    }
},
{
    path: '/login',
    name: 'login',
    component: Login,
    meta: {
        auth: false
    }
},
router.beforeEach((to, from, next) => {
    if(to.meta.auth) { //是否验证
        if(window.localStorage.access_token) { //是否登录
            next()
        } else { //未登录则跳转到登录页面
            next({
                name: 'login',
                query: {
                    redirect: to.fullPath
                }
            })
        }
    } else {
        next()
    }
})

这样你试一下

  if (window.localStorage.getItem("token")) {
        next();
     } else {
        if (to.path == '/login') { //如果是登录页面路径,就直接next()
            next();
        } else { //不然就跳转到登录;
            next({
                path: '/login',
                query: {
                    redirect: to.fullPath
                }
            })
        }
       
    }
    
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题