webfansplz / vuejs-challenges

Collection of Vue.js challenges
https://vuejs-challenges.netlify.app/
MIT License
2.7k stars 188 forks source link

17 - 计数器 #2681

Open JJczC-love opened 4 months ago

JJczC-love commented 4 months ago
<script setup lang='ts'>
import { ref } from 'vue';
import type { Ref } from 'vue';

interface UseCounterOptions {
  min?: number
  max?: number
}

function useCounter(initialValue = 0, options: UseCounterOptions = {}): { [x: string]: ((step?: number) => void) | Ref } {
  const { min, max } = options;
  const count = ref(initialValue);
  function inc(step = 1) {
    if (typeof (max) !== 'number' || (count.value + step) <= max) count.value += step
  }
  function dec(step = 1) {
    if (typeof (min) !== 'number' || (count.value - step) >= min) count.value -= step
  }
  function reset() {
    count.value = initialValue
  }
  return { count, inc, dec, reset }
}

const { count, inc, dec, reset } = useCounter(0, { min: 0, max: 10 })

</script>

<template>
  <p>Count: {{ count }}</p>
  <button @click="inc()">
    inc
  </button>
  <button @click="dec()">
    dec
  </button>
  <button @click="reset">
    reset
  </button>
</template>