From b68cdf70d6338f4e24da1531c8862766b871ebab Mon Sep 17 00:00:00 2001 From: Suven-p Date: Sun, 27 Oct 2024 19:45:43 +0545 Subject: [PATCH] Preserve query params on route change --- src/router.js | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) diff --git a/src/router.js b/src/router.js index bda5078e1..431165ecd 100644 --- a/src/router.js +++ b/src/router.js @@ -192,8 +192,24 @@ const routes = [ }, ]; -export const router = createRouter({ +const router = createRouter({ linkActiveClass: "active", history: createWebHistory(), routes, }); + +router.beforeEach((to, from) => { + // If the path is same, either the query or has has changed so avoid changing query params + // Without this check, modifying any query params will be blocked + // Check if redirectedFrom is defined to check if this function has already been run + // Without this check, the router will be stuck in an infinite loop + if (to.path !== from.path && !to.redirectedFrom) { + return { + path: to.path, + query: { ...to.query, ...from.query }, + params: to.params, + } + } +}); + +export { router };