vue-hooks-plus
Version:
Vue hooks library
60 lines (59 loc) • 1.76 kB
JavaScript
import { ref, computed, unref, watchEffect } from "vue";
import debounce from "lodash-es/debounce";
const useDebouncePlugin = (fetchInstance, { debounceWait, debounceLeading, debounceTrailing, debounceMaxWait }) => {
const debouncedRef = ref();
const options = computed(() => {
const ret = {};
const debounceLeading_ = unref(debounceLeading);
const debounceTrailing_ = unref(debounceTrailing);
const debounceMaxWait_ = unref(debounceMaxWait);
if (debounceLeading_ !== void 0) {
ret.leading = debounceLeading_;
}
if (debounceTrailing_ !== void 0) {
ret.trailing = debounceTrailing_;
}
if (debounceMaxWait_ !== void 0) {
ret.maxWait = debounceMaxWait_;
}
return ret;
});
watchEffect((onInvalidate) => {
if (unref(debounceWait)) {
const _originRunAsync = fetchInstance.runAsync.bind(fetchInstance);
debouncedRef.value = debounce(
(callback) => {
callback();
},
unref(debounceWait),
options.value
);
fetchInstance.runAsync = (...args) => {
return new Promise((resolve, reject) => {
var _a;
(_a = debouncedRef.value) == null ? void 0 : _a.call(debouncedRef, () => {
_originRunAsync(...args).then(resolve).catch(reject);
});
});
};
onInvalidate(() => {
var _a;
(_a = debouncedRef.value) == null ? void 0 : _a.cancel();
fetchInstance.runAsync = _originRunAsync;
});
}
});
if (!unref(debounceWait)) {
return {};
}
return {
name: "debouncePlugin",
onCancel: () => {
var _a;
(_a = debouncedRef.value) == null ? void 0 : _a.cancel();
}
};
};
export {
useDebouncePlugin as default
};