vue.jsrouter

Vue router path matching behaviour


Check out the code in this code Sandbox:

https://codesandbox.io/p/sandbox/vue-router-playground-forked-2rg2n8?file=%2Fsrc%2Frouter.js%3A17%2C51

Observations:

When you click on the go to users link in the application, the route's matched path changes to

/home/users

But then, when you reload this page, the route's matched path becomes

/home/:matchRest(.*)*

Is my assumption correct, that the router always matches paths from TOP to BOTTOM, and stops on the first found match?

Is there any possibility to tell the router to continue matching paths although it has already found a match?
Similar to matching functionality in a .htaccess file?


Solution

  • You are redirected to the /home/users route on click on the link because you are using a named route which correctly matches the user route.

    When reloading the page, the router checks from top to bottom the first route that matches the pattern. Which is indeed the route named home in your example.

    Vue router will return the first matched route.

    That's why we usually put the 404 path at the bottom of the routes like so :

    const routes = [
      ...allRoutes,
      { path: "*", component: PageNotFound }
    ]
    

    Meaning that if no route has matched then the 404 page will be matched and displayed.

    If you want to do some very specific matching, you can. Here's the vue router doc