vue-hooks-plus
Version:
Vue hooks library
64 lines (63 loc) • 1.74 kB
JavaScript
import { computed, unref, ref, watch, onUnmounted } from "vue";
import { throttle } from "lodash-es";
const useThrottlePlugin = (fetchInstance, { throttleWait, throttleLeading, throttleTrailing }) => {
let originThrottled = null;
const options = computed(() => {
const ret = {};
if (unref(throttleLeading) !== void 0) {
ret.leading = unref(throttleLeading);
}
if (unref(throttleTrailing) !== void 0) {
ret.trailing = unref(throttleTrailing);
}
return ret;
});
const _originRunAsync = fetchInstance.runAsync.bind(fetchInstance);
const throttled = ref();
const throttleWaitComputed = computed(() => {
return unref(throttleWait);
});
watch([throttleWaitComputed, options], (cur) => {
if (originThrottled) {
originThrottled.cancel();
fetchInstance.runAsync = _originRunAsync;
}
const [curWait, curOptions] = cur;
const _throttle = throttle(
(callback) => {
callback();
},
unref(curWait),
curOptions
);
originThrottled = _throttle;
throttled.value = _throttle;
fetchInstance.runAsync = (...args) => {
return new Promise((resolve, reject) => {
var _a;
(_a = throttled.value) == null ? void 0 : _a.call(throttled, () => {
_originRunAsync(...args).then(resolve).catch(reject);
});
});
};
}, {
immediate: true
});
if (!unref(throttleWait)) {
return {};
}
onUnmounted(() => {
var _a;
(_a = throttled.value) == null ? void 0 : _a.cancel();
});
return {
name: "throttlePlugin",
onCancel: () => {
var _a;
(_a = throttled.value) == null ? void 0 : _a.cancel();
}
};
};
export {
useThrottlePlugin as default
};