VueJS router handle all request

Viewed 78

I encounter an error, VueJS router supports all paths even those where one or more components have not been linked

const routes: RouteConfig[] = [
  { path: '/', name: 'Home', component: Home },
  { path: '/home', redirect: '/' },
  { path: '/reset-password' },
  { path: '/create', name: 'Create', component: CreateInnovation },
  { path: '/dashboard', name: 'stage-table', component: Dashboard }
];

export const createRouter = () => {
  const router = new VueRouter({
    mode: 'history',
    // @ts-ignore
    base: __dirname,
    routes
  })

  return router
}

Thanks in advance for your help, Jérémy

1 Answers

You need to create a new route, with a custom param regexp to catch all routes which haven't been defined. You'll also need to create a NotFound component to be your 404 view.

Vue 3

const routes: RouteConfig[] = [
  { path: '/', name: 'Home', component: Home },
  { path: '/home', redirect: '/' },
  { path: '/:pathMatch(.*)*', name: 'NotFound', component: NotFound },
];

Vue 2

export const new Router({
  routes: [
    ...
    {
      path: '*',
      name: '404',
      component: () => import('./views/404.vue'),
    },
  ]
});
Related