@@ -2,9 +2,11 @@ import { useRoute } from 'nuxt/app'
22
33declare const ref , watch
44
5- type QueryParamType = 'string' | 'string[]' | 'number' | 'number[]' | 'Object'
5+ type QueryParamType = 'string' | 'string[]' | 'number' | 'number[]' | 'boolean' | 'boolean[]' | 'object' | 'object[]'
6+
7+ export const useQueryRef = < T > ( key : string , defaultValue : T = null ) => {
8+ const type = getType ( defaultValue )
69
7- export const useQueryRef = ( key : string , defaultValue : any = null , type : QueryParamType = 'string' ) => {
810 const loadedValue = loadQueryParamFromURL ( key , type )
911
1012 const queryRef = ref ( loadedValue || defaultValue )
@@ -17,28 +19,37 @@ export const useQueryRef = (key: string, defaultValue: any = null, type: QueryPa
1719 { deep : true } ,
1820 )
1921
20- return queryRef
22+ return queryRef as { value : T }
2123}
2224
2325function updateQueryParamInURL ( key , value , type : QueryParamType ) {
2426 if ( typeof window == 'undefined' ) return
2527
26- if ( [ 'number[]' , 'string []' ] . includes ( type ) ) value = value . join ( ',' )
27- if ( type == 'Object' ) value = JSON . stringify ( value )
28+ if ( [ 'string[]' , ' number[]', 'boolean []' ] . includes ( type ) ) value = value . join ( ',' )
29+ if ( [ 'object' , 'object[]' ] . includes ( type ) ) value = JSON . stringify ( value )
2830
2931 const url = new URL ( window . location . href )
30- url . searchParams . set ( key , value )
32+ url . searchParams . set ( key , value . toString ( ) )
3133 url . search = decodeURIComponent ( url . search )
3234 window . history . pushState ( null , '' , url . toString ( ) )
3335}
3436
3537function loadQueryParamFromURL ( key : string , type : QueryParamType ) {
36- const loadedString = useRoute ( ) ?. query ?. [ key ] ?. toString ( ) || ''
38+ const loadedString = useRoute ( ) ?. query ?. [ key ] ?. toString ( )
3739 if ( ! loadedString ) return
3840
3941 if ( type == 'number' ) return + loadedString
4042 if ( type == 'number[]' ) return loadedString . split ( ',' ) . map ( ( n ) => + n )
4143 if ( type == 'string[]' ) return loadedString . split ( ',' )
42- if ( type == 'Object' ) return JSON . parse ( loadedString )
44+ if ( type == 'boolean' ) return loadedString == 'true'
45+ if ( type == 'boolean[]' ) return loadedString . split ( ',' ) . map ( ( n ) => n == 'true' )
46+ if ( [ 'object' , 'object[]' ] . includes ( type ) ) return JSON . parse ( loadedString )
4347 return loadedString
4448}
49+
50+ function getType ( defaultValue : any ) : QueryParamType {
51+ let _type : any = typeof defaultValue
52+ if ( _type == 'object' && defaultValue ?. length ) _type = `${ typeof defaultValue [ 0 ] } []`
53+
54+ return _type
55+ }
0 commit comments