Home > Software engineering >  Vue Router - Set default query parameters
Vue Router - Set default query parameters

Time:04-27

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?

CodePudding user response:

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.

CodePudding user response:

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

  • Related