Search code examples
vue.jsvuejs3vue-routervue-router4

Redirects in vue router v4


I'm migrating from Vue Router v3 to Vue Router v4 and bumped into an unexpected problem that breaks quite a lot of logic in my app - maybe someone faced it and knows a good solution.

In Vue Router v3 I was relying on a "chained redirect" to set the default location where each child determines where and how to redirect.

For example:

/ -> /1 -> /1/2 -> /1/2/3

No matter where user starts in this chain, their default starting position would be /1/2/3 (and this is my target behaviour)

[

        {
            path: '/',
            redirect: '/1',
        },
        {
            path: '/1',
            component: DashboardListPage,
            children: [
                {
                    path: '',
                    redirect: '2',
                },
                {
                    path: '2',
                    component: DashboardMainPage,
                    children: [
                        {
                            path: '',
                            redirect: '3'
                        },
                        {
                            path: '3',
                            component: DashboardListPage,
                        },
                    ],
                },
            ],
        },
    ],

This used to work with Vue Router v3 but seems to no longer with Vue Router v4

In Vue Router v4 it just does the following (not what I need):

  • / -> /2 (no idea why /2)
  • /1 -> /2
  • /1/2 -> /3

Again in all cases I'd expect it to redirect to /1/2/3

Is there any setting in the Vue Router v4 that I'm missing? Any hint on how to achieve that redirection behaviour is much appreciated.


Solution

  • As per reply on the similar question from the router member on github:

    This change was indeed intended: relatives paths are always resolved based on the current location to avoid inconsistencies to how Relative URLs work. In your case, the first redirect is absolute, it works, the second one is relative, it resolves to a route you don't have and then it stops. I recommend you to do one of these:

    1. use absolute paths in redirects
    2. use named routes for a deterministic route location
    3. remove the links in your application that are using any of the routes that have a redirect

    This has been overlooked in the migration guide.