From 2df6bc57f5bc319fd67b2ce35900398ece5010e0 Mon Sep 17 00:00:00 2001 From: Craig Harshbarger Date: Mon, 17 Oct 2022 10:53:20 -0500 Subject: [PATCH] stop watchers during the `beforeRouteLeave` lifecycle --- src/useRouteQueryParam/useRouteQueryParam.ts | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/src/useRouteQueryParam/useRouteQueryParam.ts b/src/useRouteQueryParam/useRouteQueryParam.ts index 3f9df9c6..d75ea610 100644 --- a/src/useRouteQueryParam/useRouteQueryParam.ts +++ b/src/useRouteQueryParam/useRouteQueryParam.ts @@ -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 export function useRouteQueryParam(param: string, defaultValue: string): Ref @@ -11,7 +11,7 @@ export function useRouteQueryParam(param: string, defaultValue: string | string[ const initialValue = matchValueType(defaultValue, getRouteQueryParam(route, param) ?? defaultValue) const valueRef = ref(initialValue) - watch(valueRef, (newValue, oldValue) => { + const unwatchValue = watch(valueRef, (newValue, oldValue) => { if (isSame(newValue, oldValue)) { return } @@ -19,7 +19,7 @@ export function useRouteQueryParam(param: string, defaultValue: string | string[ 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) @@ -29,6 +29,11 @@ export function useRouteQueryParam(param: string, defaultValue: string | string[ } }, { deep: true }) + onBeforeRouteLeave(() => { + unwatchValue() + unwatchRoute() + }) + return valueRef }