UNPKG

vue-hooks-plus

Version:
54 lines (53 loc) 1.1 kB
"use strict"; const utils = require("../utils"); const vue = require("vue"); function getTargetValue(val, options = {}) { const { min, max } = options; let target = val; if (utils.isNumber(max)) { target = Math.min(max, target); } if (utils.isNumber(min)) { target = Math.max(min, target); } return target; } function useCounter(initialValue = 0, options = {}) { const { min, max } = options; const current = vue.ref( getTargetValue(initialValue, { min, max }) ); const setValue = (value) => { const target = utils.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 [ vue.readonly(current), { inc, dec, set, reset } ]; } module.exports = useCounter;