vue-hooks-plus
Version:
Vue hooks library
57 lines (56 loc) • 1.61 kB
JavaScript
import throttle from "lodash-es/throttle";
import { ref, computed, unref, watch, onUnmounted } from "vue";
function useThrottleFn(fn, options) {
var _a, _b, _c;
let originThrottled;
const throttled = ref();
const throttleOptions = computed(() => {
var _a2;
const ret = {};
if (unref(options == null ? void 0 : options.wait) !== void 0) {
ret.wait = unref(options == null ? void 0 : options.wait);
}
if (unref(options == null ? void 0 : options.leading) !== void 0) {
ret.leading = unref(options == null ? void 0 : options.leading);
}
if (unref(options == null ? void 0 : options.trailing) !== void 0) {
ret.trailing = unref(options == null ? void 0 : options.trailing);
}
return {
...ret,
wait: (_a2 = ret == null ? void 0 : ret.wait) != null ? _a2 : 1e3
};
});
watch(throttleOptions, (cur) => {
const { wait = 1e3, ...options2 } = cur;
if (originThrottled) {
originThrottled.cancel();
originThrottled.flush();
}
const _throttle = throttle(
(...args) => {
return fn([...args]);
},
wait,
options2
);
originThrottled = _throttle;
throttled.value = _throttle;
}, {
immediate: true,
deep: true
});
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
};
}
export {
useThrottleFn as default
};