-
-
Notifications
You must be signed in to change notification settings - Fork 122
/
Copy pathuse-route-params.ts
80 lines (72 loc) · 2.05 KB
/
use-route-params.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
import { useRouteQuery as useRouteQueryBase } from "@vueuse/router";
/* eslint no-redeclare: 0 */
import type { WritableComputedRef } from "vue";
export function useRouteQuery(q: string, def: string[]): WritableComputedRef<string[]>;
export function useRouteQuery(q: string, def: string): WritableComputedRef<string>;
export function useRouteQuery(q: string, def: boolean): WritableComputedRef<boolean>;
export function useRouteQuery(q: string, def: number): WritableComputedRef<number>;
export function useRouteQuery(q: string, def: any): WritableComputedRef<any> {
const route = useRoute();
const router = useRouter();
const v = useRouteQueryBase(q, def);
const first = computed<string>(() => {
const qv = route.query[q];
if (Array.isArray(qv)) {
return qv[0]?.toString() || def;
}
return qv?.toString() || def;
});
onMounted(() => {
if (route.query[q] === undefined) {
v.value = def;
}
});
switch (typeof def) {
case "string":
return computed({
get: () => {
const qv = first.value;
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: () => {
return first.value === "true";
},
set: v => {
const query = { ...route.query, [q]: `${v}` };
router.push({ query });
},
});
case "number":
return computed({
get: () => parseInt(first.value, 10),
set: nv => {
v.value = nv.toString();
},
});
}
throw new Error("Invalid type");
}