webfansplz / vuejs-challenges

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

17 - useCounter #2177

Open cn-2k opened 11 months ago

cn-2k commented 11 months ago
<template>
  <div>
    <p>{{ count }}</p>
    <button @click="inc">Inc +</button>
    <button @click="dec">Dec -</button>
    <button @click="reset">Reset</button>
  </div>
</template>

<script setup lang='ts'>
import { ref } from 'vue'

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

/**
 * Implement the composable function
 * 1. inc (+)
 * 2. dec (-)
 * 3. reset 
 * 4. min & max opotion support
 * Make sure the function works correctly
*/
function useCounter(initialValue: number = 0, options: UseCounterOptions = {}) {
  const count = ref<number>(initialValue);

  const inc = (): void => {
    if(count.value < options.max) count.value++
  }

  const dec = (): void => {
    if(count.value > options.min) count.value--
  }

  const reset = (): void => {
    count.value = initialValue
  };

  return {count, inc, dec, reset};
}

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

</script>
sky0matic commented 5 months ago

You are increasing/decreasing the value twice per click

cn-2k commented 5 months ago

You are increasing/decreasing the value twice per click

Hahaha, true, fix'd.