Skip to content

Instantly share code, notes, and snippets.

@Akryum
Created July 10, 2024 14:12
Show Gist options
  • Save Akryum/d22899ba7b380918062c6fa65ee87f10 to your computer and use it in GitHub Desktop.
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
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))
}
@Akryum
Copy link
Author

Akryum commented Jul 10, 2024

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment