-
-
Notifications
You must be signed in to change notification settings - Fork 2.4k
/
index.ts
32 lines (31 loc) · 1.03 KB
/
index.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
import type { Ref } from 'vue-demi'
import { computed, nextTick, unref } from 'vue-demi'
import { useRoute, useRouter } from 'vue-router'
import type { ReactiveRouteOptions } from '../_types'
export function useRouteQuery(name: string): Ref<null | string | string[]>
export function useRouteQuery<T extends null | undefined | string | string[] = null | string | string[]>(name: string, defaultValue?: T, options?: ReactiveRouteOptions): Ref<T>
export function useRouteQuery<T extends string | string[]>(
name: string,
defaultValue?: T,
{
mode = 'replace',
route = useRoute(),
router = useRouter(),
}: ReactiveRouteOptions = {},
) {
return computed<any>({
get() {
const data = route.query[name]
if (data == null)
return defaultValue ?? null
if (Array.isArray(data))
return data.filter(Boolean)
return data
},
set(v) {
nextTick(() => {
router[unref(mode)]({ query: { ...route.query, [name]: v === defaultValue || v === null ? undefined : v } })
})
},
})
}