Search code examples
vue-routervue-router4

Use vue-router with catch-all/keeping original url and SPA


I am having difficulty getting vue-router to:

  • keep the original invalid url that the user typed in
  • display an embedded 404 page

From docs/examples I have seen I seem to be able to do one or the other but not both. As an example, the code below will correctly have the 404 page embedded but the URL will change to /subpage/404 instead of what the user originally put in. I have tried (unsuccessfully) using alias since I have no idea what the user is inputting that is invalid. Perhaps I was using it incorrectly or in the wrong place(s)?

Given the example code below, is this able to be done?

const routes = [{ 
  path: '/', 
  redirect: { path: '/subpage' }, 
  children: [{
    path: '/subpage',
    component: () => import ('SubPage.vue'),
    children: [{
      path: '404',
      name: '404',
      component: () => import('NotFound.vue')
    }] // Omitted other children for this example
  }]
}, {
    path: '/:pathMatch(.*)*', 
    redirect: { path: 'subpage/404' }
}];

Solution

  • Use the root catch-all to redirect to a catch-all child route of /subpage. From my testing, this should not overwrite the URL whether the invalid path is e.g. /invalidPath or /subpage/invalidPath

    const routes = [
      {
        path: '/',
        redirect: { path: '/subpage' },
        children: [
          {
            path: '/subpage',
            component: () => import('SubPage.vue'),
            children: [
              // Other omitted children
              {
                path: '/:pathMatch(.*)*',
                component: () => import('NotFound.vue')
              }
            ]
          }
        ]
      },
      {
        path: '/:pathMatch(.*)*',
        redirect: { path: `/subpage` }
      }
    ]