用多个守卫保护一个 vue 路由

Protect a vue route with multiple guards

我有一个这样的 vue 路由器:

import Vue from 'vue'
import Router from 'vue-router'

Vue.use(Router)

function guard (to, from, next) {
  if (localStorage.getItem('jwt')) {
    next()
  } else {
    next('/login')
  }
}

function admin (to, from, next) {
  if (localStorage.getItem('admin') && localStorage.getItem('admin') !== 'false' && localStorage.getItem('jwt')) {
    next()
  } else {
    next('/noadmin')
  }
}

export default new Router({

  mode: 'history',

  routes: [
    {
      path: '/',
      name: 'home',
      beforeEnter: guard,
      meta: { layout: 'default' },
      component: () => import('@/components/dashboard.vue')
    },
    {
      path: '/datacollector',
      name: 'datacollector',
      beforeEnter: guard,
      meta: { layout: 'default' },
      component: () => import('@/components/datacollector.vue')
    },
    {
      path: '/licensing',
      beforeEnter: admin,
      name: 'licensing',
      component: () => import('@/components/licensing.vue')
    },
    {
      path: '*',
      name: '404',
      component: require('@/pages/404.vue').default
    }
  ]

})

我现在的问题是,如果有条目localStorage.getItem('datacollector'),它应该只指向路径/datacollector/logout。所以当他登录的时候,登录页面把他扔到路径/datacollector。但是他应该也可以调用logout。对于其他用户,应该是允许他们调用一切。如何调整函数 guard,无论我尝试什么,我总是以循环结束。谢谢。

假设你想把用户从任何路由转到 /datacollector 路由,如果有 localStorage.getItem('datacollector') 的条目,除了 /logout 路由。

您可以简单地检查 to.path 并相应地重定向用户:

function guard (to, from, next) {
  if (localStorage.getItem('jwt')) {
    if (localStorage.getItem('datacollector')) {
      if (to.path != '/datacollector' && to.path != '/logout'){
        next('/datacollector');
      } else {
        next();
      }
    } else {
      next();
    }
  } else {
    next('/login')
  }
}