vue-hooks-plus
Version:
Vue hooks library
54 lines (53 loc) • 1.52 kB
JavaScript
;
const vue = require("vue");
const lodashEs = require("lodash-es");
const useThrottlePlugin = (fetchInstance, { throttleWait, throttleLeading, throttleTrailing }) => {
const options = vue.computed(() => {
const ret = {};
if (vue.unref(throttleLeading) !== void 0) {
ret.leading = vue.unref(throttleLeading);
}
if (vue.unref(throttleTrailing) !== void 0) {
ret.trailing = vue.unref(throttleTrailing);
}
return ret;
});
const throttledRef = vue.computed(
() => lodashEs.throttle(
(callback) => {
callback();
},
vue.unref(throttleWait),
options.value
)
);
vue.watchEffect((onInvalidate) => {
if (vue.unref(throttleWait)) {
const _originRunAsync = fetchInstance.runAsync.bind(fetchInstance);
fetchInstance.runAsync = (...args) => {
return new Promise((resolve, reject) => {
var _a;
(_a = throttledRef.value) == null ? void 0 : _a.call(throttledRef, () => {
_originRunAsync(...args).then(resolve).catch(reject);
});
});
};
onInvalidate(() => {
var _a;
fetchInstance.runAsync = _originRunAsync;
(_a = throttledRef.value) == null ? void 0 : _a.cancel();
});
}
});
if (!vue.unref(throttleWait)) {
return {};
}
return {
name: "throttlePlugin",
onCancel: () => {
var _a;
(_a = throttledRef.value) == null ? void 0 : _a.cancel();
}
};
};
module.exports = useThrottlePlugin;