vue-hooks-plus
Version:
Vue hooks library
55 lines (54 loc) • 1.08 kB
JavaScript
import { isNumber } from "../utils";
import { ref, readonly } from "vue";
function getTargetValue(val, options = {}) {
const { min, max } = options;
let target = val;
if (isNumber(max)) {
target = Math.min(max, target);
}
if (isNumber(min)) {
target = Math.max(min, target);
}
return target;
}
function useCounter(initialValue = 0, options = {}) {
const { min, max } = options;
const current = ref(
getTargetValue(initialValue, {
min,
max
})
);
const setValue = (value) => {
const target = isNumber(value) ? value : value(current.value);
current.value = getTargetValue(target, {
max,
min
});
return current.value;
};
const inc = (delta = 1) => {
setValue((c) => c + delta);
};
const dec = (delta = 1) => {
setValue((c) => c - delta);
};
const set = (value) => {
setValue(value);
};
const reset = () => {
setValue(initialValue);
};
return [
readonly(current),
{
inc,
dec,
set,
reset
}
];
}
export {
useCounter as default
};