vuejs-challenges icon indicating copy to clipboard operation
vuejs-challenges copied to clipboard

17 - 计数器

Open kalu5 opened this issue 2 years ago • 0 comments

// 你的答案
<script setup lang='ts'>
import { ref } from 'vue'

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

/**
 * Implement the composable function
 * Make sure the function works correctly
*/
function useCounter(initialValue = 0, options: UseCounterOptions = {}) {
  const count = ref<number>(initialValue)
  function inc (): void {
    if (options.max && count.value >= options.max) return
    count.value ++
  }
  
  function dec (): void {
    if (count.value <= options.min) return
    count.value --
  }
  
  function reset (): void {
    count.value = initialValue
  }
  
  return {
    count, inc, dec, reset
  }

}

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

</script>

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

kalu5 avatar Aug 31 '22 02:08 kalu5