Home > Software design >  How to use a 404 component in VUE3 single page app
How to use a 404 component in VUE3 single page app

Time:06-19

I have the following structure of the code:

router.js:

  import { createRouter, createWebHistory } from 'vue-router';

  const router = createRouter({
  history: createWebHistory(),
  routes: [
    {
      path: '/',
      name: 'App',
      component: () => import('../../src/App.vue'),
    },
    {
      path: '/:pathMatch(.*)',
      name: 'ErrorView',
      component: () => import('../components/Error.vue'),
  }
  ],
});

export default router;

App.vue

<template>
  <Land />
  <LeftNavbar />
  <Navbar />
  <Experience />
  <TechnologiesCarousel />
  <Projects />
  <Copyright />
  <BackToTop />
</template>

When I'm pressing in the URL bar: http://localhost:3000. The app is rendering properly which is fine, but when I'm trying to write a wrong URL, for eg: http://localhost:3000/abcf/ || http://localhost:3000/dsafbdmhgfjweghjfw to be redirected to the 404 page, I'm not redirected, the page still rendering the App.vue component.

Does anyone have any idea why the 404 page isn't rendered?

CodePudding user response:

Try like following /:pathMatch(.*)*:

{
  path: "/:pathMatch(.*)*",
  name: 'ErrorView',
  component: () => import('../components/Error.vue'),
},

and in App.vue place <router-view /> and move components to other view.

CodePudding user response:

I assume you are using Vue 3.

In your router file you need to change the path to this:

  {
      path: '/:pathMatch(.*)*',
      name: 'ErrorView',
      component: () => import('../components/Error.vue'),
  }

For Vue 2 the path can be: path:'*'


From Vue 2 -> 3 migration some more info for those they want to know what has changed:

Essentially, you should be able to replace the '' path with '/:pathMatch(.)*' and be good to go!

Reason: Vue Router doesn't use path-to-regexp anymore, instead it implements its own parsing system that allows route ranking and enables dynamic routing. Since we usually add one single catch-all route per project, there is no big benefit in supporting a special syntax for *.

  • Related