How to use vue js 3 route on dynamic url with 404 page?

156 Views Asked by At

I have single page site i.e xyz.com, in this page i'm checking routes for some dymanic urls and 404 page.

When i'm accessing url like xyz.com/p1, xyz.com/p2...etc. Routes are working as expected but when accessing any invalid url like xyz.com/invalid then it's redirecting correctly on NotFound component but at the same time it's updating the url.

e.g: if i access xyz.com/invalid then url get changed from xyz.com/invalid to xyz.com.

  1. How do i retain url as it is if someone access invalid url and it should redirect to NotFound component i.e 404 page.

  2. if i access url like xyz.com/invalid/ (adding extra slash at the end) then it's show blank white page instead of NotFound page ? ideally anything comes after first slash except dynamic url p1, p2, p3....etc that should redirect to NotFound page.

Any help ?

Below is the code snippet:

main.js:

Note: productArray contain 'n' no. of products.

var productArray = [
  {
    label: "product1",
    code: "p1",
  },
  {
    label: "product2",
    code: "p2",
  },
  {
    label: "product3",
    code: "p3",
  }
];

const routes = [{
    path: "/:product",
    component: Home,
    beforeEnter(to, from, next) {
      const item = to.params.lang;
      if (productArray.find((e) => e.code == product) == undefined) {
        next({ name: "notFound"});
      } else {
        return next();
      }
    },
  },
  {
    path: "/:pathMatch(.*)*",
    name: "notFound",
    component: NotFound,
  },
  {
    path: "/",
    redirect: 'p1',
  },
];

const router = createRouter({
  history: createWebHistory(),
  routes,
});

let app = createApp(App);
app.use(router);
app.mount("#app");
1

There are 1 best solutions below

5
On

preserve the current path with the params property included in your call to next

next({
  name: 'notFound',
  params: { pathMatch: to.path.substring(1).split('/') }
})