Maintain route's query when navigating between different routes

vue-router

#1

I’m using Vue router with - say - two routes:

const routes = [
    {
        path: '/alpha',
        component: AlphaComp,
    },
    {
        path: '/beta',
        component: BetaComp,
    },
];

And a menu-bar that has:

<router-link to="/alpha">
<router-link to="/beta">

Now, these components respond to route changes through the beforeRouteUpdate hook.

When I am on /alpha?some=param, and I click on the second link, I will navigate to /beta.
Then, when clicking on the first link I would like to navigate back to /alpha?some=param but I am navigating to /alpha instead, resetting my query parameters.

How can I achieve that routes maintain their parameters throughout navigation.


#2

Well, if you hit the browsers Back button you should have the query, but if you navigate to it as a link then it’s technically a new item in the history stack. You could probably hack together some way of pushing the query string onto the navigation element, but that would be very messy. The clean way to maintain state is to use state management such as Vuex. So if you return to a route that already has a certain state then you can restore it.