Skip to content

Commit

Permalink
stop watchers during the beforeRouteLeave lifecycle
Browse files Browse the repository at this point in the history
  • Loading branch information
pleek91 committed Oct 17, 2022
1 parent 56ee8ef commit 2df6bc5
Showing 1 changed file with 8 additions and 3 deletions.
11 changes: 8 additions & 3 deletions src/useRouteQueryParam/useRouteQueryParam.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
/* eslint-disable no-redeclare */
import { Ref, ref, watch } from 'vue'
import { RouteLocationNormalized, useRoute, useRouter } from 'vue-router'
import { onBeforeRouteLeave, RouteLocationNormalized, useRoute, useRouter } from 'vue-router'

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

watch(valueRef, (newValue, oldValue) => {
const unwatchValue = watch(valueRef, (newValue, oldValue) => {
if (isSame(newValue, oldValue)) {
return
}

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

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

onBeforeRouteLeave(() => {
unwatchValue()
unwatchRoute()
})

return valueRef
}

Expand Down

0 comments on commit 2df6bc5

Please sign in to comment.