Skip to content

Commit e831f49

Browse files
committed
fix: bug where defaultValue would overwrite and therefore break the updating in URL when compared if value not equals defaultValue
1 parent abb422a commit e831f49

File tree

2 files changed

+30
-10
lines changed

2 files changed

+30
-10
lines changed

playground/app.vue

Lines changed: 19 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,26 @@
11
<template>
22
<div class="bg-black text-white w-screen h-screen p-4">
3-
<input
4-
v-model="name"
5-
type="text"
6-
placeholder="Type name"
7-
class="bg-transparent border border-white px-4 py-2 rounded-md"
8-
>
3+
<pre>{{ name }}</pre>
4+
5+
<br>
6+
<br>
7+
<button @click="change()">
8+
Change
9+
</button>
10+
<br>
11+
<button @click="reset()">
12+
Reset
13+
</button>
914
</div>
1015
</template>
1116

1217
<script setup lang="ts">
13-
const name = queryRef('name', '')
18+
const name = queryRef('name', ['Lukas', 'Ipsum'])
19+
20+
const change = () => {
21+
name.value[0] = 'Max'
22+
}
23+
const reset = () => {
24+
name.value = ['Lukas', 'Ipsum']
25+
}
1426
</script>

src/runtime/composables/queryRef.ts

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ type QueryParamType = 'string' | 'string[]' | 'number' | 'number[]' | 'boolean'
55

66
export const queryRef = <T>(key: string, defaultValue: T | null = null) => {
77
const type = getType(defaultValue)
8+
const fixedDefaultValue = JSON.parse(JSON.stringify(defaultValue))
89

910
const loadedValue = loadQueryParamFromURL(key, type)
1011

@@ -13,7 +14,7 @@ export const queryRef = <T>(key: string, defaultValue: T | null = null) => {
1314
watch(
1415
queryRef,
1516
async (newVal) => {
16-
updateQueryParamInURL(key, newVal, defaultValue, type)
17+
updateQueryParamInURL(key, newVal, fixedDefaultValue, type)
1718
},
1819
{ deep: true },
1920
)
@@ -24,8 +25,8 @@ export const queryRef = <T>(key: string, defaultValue: T | null = null) => {
2425
function updateQueryParamInURL(key, value, defaultValue, type: QueryParamType) {
2526
if (typeof window == 'undefined') return
2627

27-
if (['string[]', 'number[]', 'boolean[]'].includes(type)) value = value.join(',')
28-
if (['object', 'object[]'].includes(type)) value = JSON.stringify(value)
28+
value = valueToString(value, type)
29+
defaultValue = valueToString(defaultValue, type)
2930

3031
const url = new URL(window.location.href)
3132
if (value != defaultValue) {
@@ -57,3 +58,10 @@ function getType(defaultValue: any): QueryParamType {
5758

5859
return _type
5960
}
61+
62+
function valueToString(value, type): string {
63+
if (['string[]', 'number[]', 'boolean[]'].includes(type)) value = value.join(',')
64+
if (['object', 'object[]'].includes(type)) value = JSON.stringify(value)
65+
66+
return value
67+
}

0 commit comments

Comments
 (0)