Search code examples
vue.jsvuejs3vue-routervue-router4

Vue router order of routes from .getRoutes()


I'm using the following router configuration:

const router = createRouter({
    history: createWebHistory(import.meta.env.BASE_URL),
    routes: [
        {
            path: '/home',
            name: 'Home',
            component: HomeView,
        },
        {
            path: '/dev',
            name: 'Dev',
            component: DevView,
        },
        {
            path: '/dev/components',
            name: 'Components',
            component: ComponentsView,
        },
    ],
});

And when I try to access the router's routes using

router.getRoutes()

The routes are ordered like this:

DevComponents
Home
Dev

I would expect them to be ordered in the same order as how they were defined. Am I doing something wrong or is there something I can do to have the routes ordered in the order they were defined in? So like this:

Home
Dev
DevComponents

I think it has something to do with the route's path because if I change the DevComponent's path to '/components' it's ordered the way I want it to be.

Update:

The reason I want the routes to be ordered in this order is because I want to make a dynamic sidebar navigation component. This component will receive this array and then loop over every item and make navigation items in the order the routes were defined.

So this is my current result:

enter image description here


Solution

  • If you want the routes in the same order as you defined them in your router.js, you can use: router.options.routes. It gives you an array with the initial routes you declared. Then you can loop through this object to get the name and the path of each route.