【问题标题】:Guarding child routes in vuejs在 vuejs 中保护子路由
【发布时间】:2017-11-25 11:43:49
【问题描述】:

我试图保护子路由免受父路由的影响,但这失败了

    export default new Router({
    routes: [
    //frontend routes
    {
      {path: 'auth', component: Auth, children: authroutes,
        beforeEnter: (to, from, next) => {
        // check if user is a guest or loggedin
        auth.canAccess(permissions.is_guest)
          .then((res) => {
            if (res.data.status) {
              next();
            } else {
              router.push('/auth/not-allowed');
            }
          })
       }}
      ]
     }
   ]
 })

现在在我的孩子路线上

authroutes.js

const authroutes = [
  {path: '', redirect: 'login'},
  {path: 'login', component: Login, name: "login" },
];

但是当我将上面的 beforeenter 放在子路由上时,它可以工作,但会导致很多代码重复。

我怎样才能保护孩子远离父路线

例如:守卫 /auth/login 和 /auth/register

【问题讨论】:

    标签: javascript vue.js vuejs2


    【解决方案1】:

    只需将路由的元字段用于您要保护的字段,如下所示:

    const authroutes = [
        {path: '', redirect: 'login', meta: {requiresAuth: true}},
        {path: 'login', component: Login, name: "login" , meta: {requiresAuth: true}},,
    ];
    

    然后配置您的路由器以检查路由是否具有指定的元字段并执行您的重定向逻辑

    router.beforeEach((to, from, next) => { 
        if (to.matched.some(record => record.meta.requiresAuth)) { 
            auth.canAccess(permissions.is_guest)
                  .then((res) => {
                    if (res.data.status) {
                          next();
                    } else {
                         next('/auth/not-allowed');
                    }
                  })
        }else { 
            next() // make sure to always call next()! 
        } 
    });
    

    在此处查看更多信息:Route meta fields

    【讨论】:

    • @GEOFFREYMWANGI 是 auth.canAccess(permissions.is_guest) 您的服务器或数据库的异步方法?
    • itsan async 方法返回一个 promise,从服务器中的 db 检查到带有 mysql db 的 php 服务器
    【解决方案2】:

    这是另一种方式:

    {
      path: '/dashboard',
      name: 'dashboard',
      component: Dashboard,
      children: [
    
        {
          path: 'child',
          name: 'child',
          component: Child
        }
      ],
      beforeEnter(to, from, next) { // => using before enter
        if (is_user_logged()) {
          next()
        }else {
          next({name: 'not_found'}) //=> redirecting to another page
        }
      }
    }, 
    

    注意is_user_logged()是一个检查用户是否登录的函数。我更喜欢这样做:

    is_user_logged: () => !!localStorage.getItem('token')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-02-10
      • 2020-02-08
      • 2021-08-17
      • 2017-02-11
      • 2016-02-11
      • 1970-01-01
      • 1970-01-01
      • 2019-02-10
      相关资源
      最近更新 更多