1- import { computed , unref , watchEffect } from 'vue'
1+ import { computed , onUnmounted , ref , unref , watch } from 'vue'
22import { type DebouncedFunc , type ThrottleSettings } from 'lodash-es'
33import { throttle } from 'lodash-es'
44import { UseRequestPlugin } from '../types'
@@ -7,6 +7,9 @@ const useThrottlePlugin: UseRequestPlugin<unknown, unknown[]> = (
77 fetchInstance ,
88 { throttleWait, throttleLeading, throttleTrailing } ,
99) => {
10+
11+ let originThrottled : DebouncedFunc < any > | null = null
12+
1013 const options = computed ( ( ) => {
1114 const ret : ThrottleSettings = { }
1215 if ( unref ( throttleLeading ) !== undefined ) {
@@ -18,44 +21,51 @@ const useThrottlePlugin: UseRequestPlugin<unknown, unknown[]> = (
1821 return ret
1922 } )
2023
21- // @ts -ignore
22- const throttledRef = computed < DebouncedFunc < any > > ( ( ) =>
23- throttle (
24- ( callback : ( ) => void ) => {
24+ const _originRunAsync = fetchInstance . runAsync . bind ( fetchInstance )
25+ const throttled = ref < DebouncedFunc < any > > ( )
26+
27+ watch ( [ throttleWait , options ] , ( cur ) => {
28+ if ( originThrottled ) {
29+ originThrottled . cancel ( )
30+ fetchInstance . runAsync = _originRunAsync
31+ }
32+ const [ curWait , curOptions ] = cur
33+ const _throttle = throttle (
34+ ( callback : any ) => {
2535 callback ( )
2636 } ,
27- unref ( throttleWait ) ,
28- options . value ,
29- ) ,
30- )
31-
32- watchEffect ( onInvalidate => {
33- if ( unref ( throttleWait ) ) {
34- const _originRunAsync = fetchInstance . runAsync . bind ( fetchInstance )
35- fetchInstance . runAsync = ( ...args ) => {
36- return new Promise ( ( resolve , reject ) => {
37- throttledRef . value ?.( ( ) => {
38- _originRunAsync ( ...args )
39- . then ( resolve )
40- . catch ( reject )
41- } )
37+ // @ts -ignore
38+ unref ( curWait ) ,
39+ // @ts -ignore
40+ curOptions ,
41+ )
42+ originThrottled = _throttle
43+ throttled . value = _throttle
44+ fetchInstance . runAsync = ( ...args ) => {
45+ return new Promise ( ( resolve , reject ) => {
46+ throttled . value ?.( ( ) => {
47+ _originRunAsync ( ...args )
48+ . then ( resolve )
49+ . catch ( reject )
4250 } )
43- }
44- onInvalidate ( ( ) => {
45- fetchInstance . runAsync = _originRunAsync
46- throttledRef . value ?. cancel ( )
4751 } )
4852 }
53+ } , {
54+ immediate : true ,
4955 } )
5056
5157 if ( ! unref ( throttleWait ) ) {
5258 return { }
5359 }
5460
61+ onUnmounted ( ( ) => {
62+ throttled . value ?. cancel ( )
63+ } )
64+
5565 return {
5666 name : "throttlePlugin" ,
5767 onCancel : ( ) => {
58- throttledRef . value ?. cancel ( )
68+ throttled . value ?. cancel ( )
5969 } ,
6070 }
6171}
0 commit comments