11/* eslint-disable no-redeclare */
22import { Ref , ref , watch } from 'vue'
3- import { RouteLocationNormalized , useRoute , useRouter } from 'vue-router'
3+ import { onBeforeRouteLeave , RouteLocationNormalized , useRoute , useRouter } from 'vue-router'
44
55export function useRouteQueryParam ( param : string ) : Ref < string | string [ ] >
66export 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