Оценок пока нет Clear trailing slash in vue-router app

Hello everyone. In this post i ant talk about process of clearing trailing slash in url of vue app with vue-router plugin

Let’s say we have such a router

 ...
 routes: [
    {
      path: "/",
      name: "home",
      component: Home,
      children: [
        {
          path: "/guide",
          name: "guide",
          component: () => import("./components/Guide.vue"),
          children: [
            {
              path: "/guide/javascript",
              name: "javascript",
              component: () => import("./components/JavaScript.vue")
            },
            {
              path: "/guide/csharp",
              name: "csharp",
              component: () => import("./components/CSharp.vue")
            }
          ]
        },
        {
          path: "/service",
          name: "service",
          component: () => import("./components/Service.vue")
        }
      ]
    },
    { path: "*", component: () => import("./components/404.vue") }
  ]
...

There are no errors in this code, this is, rather, a flaw in the view-router plugin that cannot process the last slash. In the documentation, you may be prompted to use the property pathToRegexpOptions: { strict: true }. But he won’t help you because he didn’t help me. If you have an option on how to use it correctly, write in the comments.

To fix this, let’s rewrite the router method router.beforeEach(to, from, next)

...
router.beforeEach((to, from, next) => {
  const _to = to.fullPath.replace(/\/$/, "");
  //const _from = from.fullPath.replace(/\/$/, "");
  //const _current = window.location.pathname.replace(/\/$/, "");
  const flag = _to !== "" && to.fullPath && to.fullPath.match(/\/$/);
  if (flag) {
    let _to2 = "";
    for (let i = 1; i < to.fullPath.split(/\//).length - 1; i++) {
      _to2 += "/" + to.fullPath.split(/\//)[i];
    }
    next(_to2);
  } else next();
});
...

The full code example ypu can find in my codesandbox

Пожалуйста, оцените материал

WebSofter

Web - технологии