Skip to content

Commit 31199ab

Browse files
committed
imp: reset URL Param if value equals defaultValue
1 parent d661312 commit 31199ab

File tree

1 file changed

+9
-5
lines changed

1 file changed

+9
-5
lines changed

src/runtime/composables/queryRef.ts

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -14,22 +14,26 @@ export const queryRef = <T>(key: string, defaultValue: T = null) => {
1414
watch(
1515
queryRef,
1616
async (newVal) => {
17-
updateQueryParamInURL(key, newVal, type)
17+
updateQueryParamInURL(key, newVal, defaultValue, type)
1818
},
1919
{ deep: true },
2020
)
2121

2222
return queryRef as { value: T }
2323
}
2424

25-
function updateQueryParamInURL(key, value, type: QueryParamType) {
25+
function updateQueryParamInURL(key, value, defaultValue, type: QueryParamType) {
2626
if (typeof window == 'undefined') return
2727

2828
if (['string[]', 'number[]', 'boolean[]'].includes(type)) value = value.join(',')
2929
if (['object', 'object[]'].includes(type)) value = JSON.stringify(value)
3030

3131
const url = new URL(window.location.href)
32-
url.searchParams.set(key, value.toString())
32+
if (value != defaultValue) {
33+
url.searchParams.set(key, value.toString())
34+
} else {
35+
url.searchParams.delete(key)
36+
}
3337
url.search = decodeURIComponent(url.search)
3438
window.history.pushState(null, '', url.toString())
3539
}
@@ -39,10 +43,10 @@ function loadQueryParamFromURL(key: string, type: QueryParamType) {
3943
if (!loadedString) return
4044

4145
if (type == 'number') return +loadedString
42-
if (type == 'number[]') return loadedString.split(',').map(n => +n)
46+
if (type == 'number[]') return loadedString.split(',').map((n) => +n)
4347
if (type == 'string[]') return loadedString.split(',')
4448
if (type == 'boolean') return loadedString == 'true'
45-
if (type == 'boolean[]') return loadedString.split(',').map(n => n == 'true')
49+
if (type == 'boolean[]') return loadedString.split(',').map((n) => n == 'true')
4650
if (['object', 'object[]'].includes(type)) return JSON.parse(loadedString)
4751
return loadedString
4852
}

0 commit comments

Comments
 (0)