Skip to content

Commit 7b8ee5a

Browse files
authored
Merge pull request #112 from PrefectHQ/unmount-watchers
BugFix: stop watchers during the `beforeRouteLeave` lifecycle
2 parents 56ee8ef + 2df6bc5 commit 7b8ee5a

File tree

1 file changed

+8
-3
lines changed

1 file changed

+8
-3
lines changed

src/useRouteQueryParam/useRouteQueryParam.ts

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
/* eslint-disable no-redeclare */
22
import { Ref, ref, watch } from 'vue'
3-
import { RouteLocationNormalized, useRoute, useRouter } from 'vue-router'
3+
import { onBeforeRouteLeave, RouteLocationNormalized, useRoute, useRouter } from 'vue-router'
44

55
export function useRouteQueryParam(param: string): Ref<string | string[]>
66
export function useRouteQueryParam(param: string, defaultValue: string): Ref<string>
@@ -11,15 +11,15 @@ export function useRouteQueryParam(param: string, defaultValue: string | string[
1111
const initialValue = matchValueType(defaultValue, getRouteQueryParam(route, param) ?? defaultValue)
1212
const valueRef = ref<string | string[]>(initialValue)
1313

14-
watch(valueRef, (newValue, oldValue) => {
14+
const unwatchValue = watch(valueRef, (newValue, oldValue) => {
1515
if (isSame(newValue, oldValue)) {
1616
return
1717
}
1818

1919
router.push({ query: { ...route.query, [param]: valueRef.value } })
2020
})
2121

22-
watch(route, (newRoute, oldRoute) => {
22+
const unwatchRoute = watch(route, (newRoute, oldRoute) => {
2323
const newValue = getRouteQueryParam(newRoute, param) ?? defaultValue
2424
const oldValue = getRouteQueryParam(oldRoute, param) ?? defaultValue
2525
const matched = matchValueType(oldValue, newValue)
@@ -29,6 +29,11 @@ export function useRouteQueryParam(param: string, defaultValue: string | string[
2929
}
3030
}, { deep: true })
3131

32+
onBeforeRouteLeave(() => {
33+
unwatchValue()
34+
unwatchRoute()
35+
})
36+
3237
return valueRef
3338
}
3439

0 commit comments

Comments
 (0)