在vuejs守卫儿童路线

时间:2017-11-25 11:43:49

标签: javascript vue.js vuejs2

我试图保护来自父路线的子路线,但这失败了

public void resolveConf(string workspaceName, IWin32Window parent)
    {

        var workspace = VersionControlServer.GetWorkspace(workspaceName, ".");

        var controlsAssembly = Assembly.GetAssembly(typeof(ControlAddItemsExclude));
        var vcResolveCoinflictsDialogType = controlsAssembly.GetType("Microsoft.TeamFoundation.VersionControl.Controls.DialogResolveConflicts");
        var ci = vcResolveCoinflictsDialogType.GetConstructor(
            BindingFlags.Instance | BindingFlags.Public,
            null,
            new[] { typeof(Workspace), typeof(string[]), typeof(bool) },
            null);
        var resolveCoinflictsDialog = (Form)ci.Invoke(new object[] { workspace, null, true });
        resolveCoinflictsDialog.ShowDialog(parent);
    }

现在我的孩子路线

    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');
            }
          })
       }}
      ]
     }
   ]
 })

但是当我将上述内容放在子路线上时,它会起作用,但会导致很多代码重复。

我如何保护孩子远离父路线

例如:guard / auth / login和authroutes.js const authroutes = [ {path: '', redirect: 'login'}, {path: 'login', component: Login, name: "login" }, ];

2 个答案:

答案 0 :(得分:3)

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

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

答案 1 :(得分:1)

  

这是另一种方式:

{
  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')