Created
July 10, 2024 14:12
-
-
Save Akryum/d22899ba7b380918062c6fa65ee87f10 to your computer and use it in GitHub Desktop.
Reactive Url Query read & write object that can be used in Nuxt and in several components at the same time
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { useUrlSearchParams as useVueUseUrlSearchParams } from '@vueuse/core' | |
const paramsInstances = new Map<string, ReturnType<typeof useVueUseUrlSearchParams>>() | |
export function useRouteQuery<T extends Record<string, any> = Record<string, any>>(key?: string) { | |
if (import.meta.server) { | |
return useRoute().query as T | |
} | |
const finalKey = key ?? window.location.pathname | |
if (!paramsInstances.has(finalKey)) { | |
paramsInstances.set(finalKey, useVueUseUrlSearchParams('history')) | |
} | |
const query = paramsInstances.get(finalKey)! as T | |
Object.assign(query, getUrlQuery()) | |
return query | |
} | |
function getUrlQuery() { | |
return Object.fromEntries(new URLSearchParams(window.location.search)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
See vueuse/vueuse#3759