How to Reset Filters with Query Params Without Triggering Navigation Guard Loops? #2436
-
Hello, I have a design issue with my Vue Router setup. I’m working on dashboard pages that contain dynamic filters, which are stored in a Pinia store. The query params in the URLs of my dashboards are updated to reflect the active filters. This allows filters to persist when the page is reloaded or if the URL with query params is shared with another user. I’m using a watcher in my Pinia store to handle this: const queryParams = computed(() => {
return {
themes: selectedThemesKeys.value.join(),
sources: selectedSourcesKeys.value.join(),
presetPeriod: selectedPresetPeriod.value,
customStart: customPeriod.value.start,
customEnd: customPeriod.value.end,
}
})
watch(queryParams, () => {
router.replace({ query: queryParams.value })
}) Now, I would like to reset the filters when the user navigates to a new dashboard. I tried adding something like this in a router.beforeEach(async (to, from) => {
if (from.name && to.name !== from.name) {
const filtersStore = useFiltersStore()
filtersStore.$reset()
}
}) The issue is that I believe using watch(
queryParams,
(query) => {
const newRouteLocation = router.resolve({ query })
history.replaceState(history.state, '', newRouteLocation.fullPath)
}
) How can I properly reset the filters when switching dashboards ? Thank you for your help! |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 4 replies
-
Since you are in a navigation guard, you can trigger a redirect: router.beforeEach(async (to, from) => {
if (from.name && to.name !== from.name && to.name === 'dashboard' && !to.redirectedFrom) {
return { ...to, query: {} }
}
}) |
Beta Was this translation helpful? Give feedback.
Since you are in a navigation guard, you can trigger a redirect: