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

17 - 计数器

Open PoliWen opened this issue 3 years ago • 0 comments

<script setup lang='ts'>
import {ref,unref} 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 { min, max } = options
  const count = ref(initialValue)
  const inc = ()=> { count.value = Math.min(unref(count) + 1, max)  }
  const dec = ()=> { count.value = Math.max(unref(count) - 1, min)  }
  const 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>

PoliWen avatar Sep 10 '22 03:09 PoliWen