@@ -2,37 +2,43 @@ import { useRoute } from 'nuxt/app'
22
33declare const ref , watch
44
5- export const useQueryRef = ( key : string , defaultValue : any = null ) : any => {
6- const loadedValue = loadQueryParamFromURL ( key )
5+ type QueryParamType = 'string' | 'string[]' | 'number' | 'number[]' | 'Object'
6+
7+ export const useQueryRef = ( key : string , defaultValue : any = null , type : QueryParamType = 'string' ) => {
8+ const loadedValue = loadQueryParamFromURL ( key , type )
79
810 const queryRef = ref ( loadedValue || defaultValue )
911
1012 watch (
1113 queryRef ,
1214 async ( newVal ) => {
13- updateQueryParamInURL ( key , newVal , defaultValue )
15+ updateQueryParamInURL ( key , newVal , type )
1416 } ,
1517 { deep : true } ,
1618 )
1719
1820 return queryRef
1921}
2022
21- function updateQueryParamInURL ( key , value , defaultValue ) {
23+ function updateQueryParamInURL ( key , value , type : QueryParamType ) {
2224 if ( typeof window == 'undefined' ) return
2325
24- const url = new URL ( window . location . href )
25-
26- if ( value == defaultValue ) {
27- url . searchParams . delete ( key )
28- } else {
29- url . searchParams . set ( key , value )
30- }
26+ if ( [ 'number[]' , 'string[]' ] . includes ( type ) ) value = value . join ( ',' )
27+ if ( type == 'Object' ) value = JSON . stringify ( value )
3128
29+ const url = new URL ( window . location . href )
30+ url . searchParams . set ( key , value )
3231 url . search = decodeURIComponent ( url . search )
3332 window . history . pushState ( null , '' , url . toString ( ) )
3433}
3534
36- function loadQueryParamFromURL ( key : string ) : string | undefined {
37- return useRoute ( ) ?. query ?. [ key ] ?. toString ( )
35+ function loadQueryParamFromURL ( key : string , type : QueryParamType ) {
36+ const loadedString = useRoute ( ) ?. query ?. [ key ] ?. toString ( ) || ''
37+ if ( ! loadedString ) return
38+
39+ if ( type == 'number' ) return + loadedString
40+ if ( type == 'number[]' ) return loadedString . split ( ',' ) . map ( ( n ) => + n )
41+ if ( type == 'string[]' ) return loadedString . split ( ',' )
42+ if ( type == 'Object' ) return JSON . parse ( loadedString )
43+ return loadedString
3844}
0 commit comments