vue-hooks-plus
Version:
Vue hooks library
61 lines (60 loc) • 1.97 kB
JavaScript
const vue = require("vue");
const debounce = require("lodash-es/debounce");
const _interopDefaultLegacy = (e) => e && typeof e === "object" && "default" in e ? e : { default: e };
const debounce__default = /* @__PURE__ */ _interopDefaultLegacy(debounce);
const useDebouncePlugin = (fetchInstance, { debounceWait, debounceLeading, debounceTrailing, debounceMaxWait }) => {
const debouncedRef = vue.ref();
const options = vue.computed(() => {
const ret = {};
const debounceLeading_ = vue.unref(debounceLeading);
const debounceTrailing_ = vue.unref(debounceTrailing);
const debounceMaxWait_ = vue.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;
});
vue.watchEffect((onInvalidate) => {
if (vue.unref(debounceWait)) {
const _originRunAsync = fetchInstance.runAsync.bind(fetchInstance);
debouncedRef.value = debounce__default.default(
(callback) => {
callback();
},
vue.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 (!vue.unref(debounceWait)) {
return {};
}
return {
name: "debouncePlugin",
onCancel: () => {
var _a;
(_a = debouncedRef.value) == null ? void 0 : _a.cancel();
}
};
};
module.exports = useDebouncePlugin;
;