Vue-Router Abstract Parent Routes

前端 未结 1 2137
走了就别回头了
走了就别回头了 2021-02-20 13:50

I am trying to migrate my current site to vuejs. The site map must be:

/login
/signup
/password-reset
/browse
/search
... dozens of other routes
<
1条回答
  •  梦毁少年i
    2021-02-20 14:24

    Whenever more than one route shares the same path, the first route in the array takes priority. So you need to put the Home route before the Auth route. That way, the / path will always match the Home route and not the Auth route. That also means that it is impossible to route directly to the Auth route, which is what you want.

    If you do not want the Home route to be accessible, you can specify a redirect that should occur when it is matched exactly:

    {
      path: '/',
      component: Home,
      redirect: '/browse',           // Redirect to path, or
      redirect: { name: 'browse' },  // Redirect to named route
      children: ...
    }
    

    If your Auth component has no auth-specific UI, you mightn't want to use "abstract" routes like this to enforce the authentication. There's plenty of information about how to achieve this in vue-router; here's one way:

    // Routes
    
    {
      path: '/profile',
      component: Profile,
      meta: { auth: true },
    }
    
    // Router hooks
    
    router.beforeEach((to, from, next) => {
      if (to.matched.some(route => route.meta.auth) && !authenticated) {
        next('/login');
      } else {
        next();
      }
    });
    

    0 讨论(0)
提交回复
热议问题