vue-hooks-plus
Version:
Vue hooks library
58 lines (57 loc) • 1.82 kB
JavaScript
const throttle = require("lodash-es/throttle");
const vue = require("vue");
const _interopDefaultLegacy = (e) => e && typeof e === "object" && "default" in e ? e : { default: e };
const throttle__default = /* @__PURE__ */ _interopDefaultLegacy(throttle);
function useThrottleFn(fn, options) {
var _a, _b, _c;
let originThrottled;
const throttled = vue.ref();
const throttleOptions = vue.computed(() => {
var _a2;
const ret = {};
if (vue.unref(options == null ? void 0 : options.wait) !== void 0) {
ret.wait = vue.unref(options == null ? void 0 : options.wait);
}
if (vue.unref(options == null ? void 0 : options.leading) !== void 0) {
ret.leading = vue.unref(options == null ? void 0 : options.leading);
}
if (vue.unref(options == null ? void 0 : options.trailing) !== void 0) {
ret.trailing = vue.unref(options == null ? void 0 : options.trailing);
}
return {
...ret,
wait: (_a2 = ret == null ? void 0 : ret.wait) != null ? _a2 : 1e3
};
});
vue.watch(throttleOptions, (cur) => {
const { wait = 1e3, ...options2 } = cur;
if (originThrottled) {
originThrottled.cancel();
originThrottled.flush();
}
const _throttle = throttle__default.default(
(...args) => {
return fn([...args]);
},
wait,
options2
);
originThrottled = _throttle;
throttled.value = _throttle;
}, {
immediate: true,
deep: true
});
vue.onUnmounted(() => {
var _a2;
(_a2 = throttled.value) == null ? void 0 : _a2.cancel();
});
return {
run: (_a = throttled.value) != null ? _a : () => {
},
cancel: (_b = throttled.value) == null ? void 0 : _b.cancel,
flush: (_c = throttled.value) == null ? void 0 : _c.flush
};
}
module.exports = useThrottleFn;
;