'Vue Router - Set default query parameters

I'm implementing an paginated list. Therefore I'm using query parameters like ?size=10. This query paramter needs to be always inside my URL (like /home?size=2).

This apporach is not working:

const routes = [{ path: "/home", query: { size: "10" }, components: MyPage }];
const router = createRouter({
  history: createWebHistory(),
  routes,
}); 

I thought it is instantiating the route with some parameters. Looking into the Routing section of vue devtools shows me an empty query object:

$route:/home
  fullPath:"/home"
  path:"/home
  query:Object (empty)
  hash:""
  name:undefined
  params:Object (empty)
  matched:Array[0]
  meta:Object (empty)
  redirectedFrom:undefined
  href:"/home

How can I set a default query param to my route?



Solution 1:[1]

Here is a proposal using the beforeEach NavigationGuard:

const routes = [{ path: "/home", name: "Home", components: MyPage }];

const router = createRouter({
  history: createWebHistory(),
  routes,
}); 

router.beforeEach((to, from) => {
  if(to.name === "Home" && !to.query.hasOwnProperty("size")){
      to.query.size = "10"
  }
})

The idea is to add to the route a default query parameter for size when it is not there.

Solution 2:[2]

The only way to achieve this properly without defining the default value in every router.push() is probably with Navigation Gurads. You can use them to get the query-parameters that are currently in the url, add the default query-params you need and then return the new route.

Though I would not do it, this is probably the easiest way to achieve this.

And if you want to make them customizable via pinia/vuex you would need to set up a store and make a user input to change the setting.

Note: Pinia is most likely the better option, because it is newer and will still be supported far in the future

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Nechoj
Solution 2 h0p3zZ