From b7aacb3cde9d63d2e58ca28ddc27ebca99e9c1e4 Mon Sep 17 00:00:00 2001 From: Hayden <64056131+hay-kot@users.noreply.github.com> Date: Tue, 1 Nov 2022 21:58:46 -0800 Subject: [PATCH] feat: encode search into url (#131) * route query helper * encode search parameters into url --- frontend/composables/use-route-params.ts | 60 ++++++++++++++++ frontend/pages/items.vue | 87 ++++++++++++++++++++---- 2 files changed, 135 insertions(+), 12 deletions(-) create mode 100644 frontend/composables/use-route-params.ts diff --git a/frontend/composables/use-route-params.ts b/frontend/composables/use-route-params.ts new file mode 100644 index 0000000..d38f409 --- /dev/null +++ b/frontend/composables/use-route-params.ts @@ -0,0 +1,60 @@ +/* eslint no-redeclare: 0 */ +import { WritableComputedRef } from "vue"; + +export function useRouteQuery(q: string, def: string[]): WritableComputedRef; +export function useRouteQuery(q: string, def: string): WritableComputedRef; +export function useRouteQuery(q: string, def: boolean): WritableComputedRef; +// eslint-disable-next-line @typescript-eslint/no-explicit-any +export function useRouteQuery(q: string, def: any): WritableComputedRef { + const route = useRoute(); + const router = useRouter(); + + switch (typeof def) { + case "string": + if (route.query[q] === undefined) { + router.push({ query: { ...route.query, [q]: def } }); + } + + return computed({ + get: () => { + const qv = route.query[q]; + if (Array.isArray(qv)) { + return qv[0]; + } + return qv; + }, + set: v => { + const query = { ...route.query, [q]: v }; + router.push({ query }); + }, + }); + case "object": // array + return computed({ + get: () => { + const qv = route.query[q]; + if (Array.isArray(qv)) { + return qv; + } + return [qv]; + }, + set: v => { + const query = { ...route.query, [q]: v }; + router.push({ query }); + }, + }); + case "boolean": + return computed({ + get: () => { + const qv = route.query[q]; + if (Array.isArray(qv)) { + return qv[0] === "true"; + } + return qv === "true"; + }, + set: v => { + const query = { ...route.query, [q]: `${v}` }; + router.push({ query }); + }, + }); + } +} diff --git a/frontend/pages/items.vue b/frontend/pages/items.vue index b61d940..f8558ff 100644 --- a/frontend/pages/items.vue +++ b/frontend/pages/items.vue @@ -1,5 +1,6 @@