vue-hooks-plus
Version:
Vue hooks library
63 lines (62 loc) • 1.76 kB
JavaScript
const vue = require("vue");
const lodashEs = require("lodash-es");
const useThrottlePlugin = (fetchInstance, { throttleWait, throttleLeading, throttleTrailing }) => {
let originThrottled = null;
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 _originRunAsync = fetchInstance.runAsync.bind(fetchInstance);
const throttled = vue.ref();
const throttleWaitComputed = vue.computed(() => {
return vue.unref(throttleWait);
});
vue.watch([throttleWaitComputed, options], (cur) => {
if (originThrottled) {
originThrottled.cancel();
fetchInstance.runAsync = _originRunAsync;
}
const [curWait, curOptions] = cur;
const _throttle = lodashEs.throttle(
(callback) => {
callback();
},
vue.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 (!vue.unref(throttleWait)) {
return {};
}
vue.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();
}
};
};
module.exports = useThrottlePlugin;
;