[Vuejs]-Vue Router – Set default query parameters

3πŸ‘

βœ…

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.

πŸ‘€Nechoj

1πŸ‘

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

πŸ‘€h0p3zZ

Leave a comment