Skip to content

17 - 计数器 #1985

Open
Open
@gaoshunpeng

Description

@gaoshunpeng
<script setup lang='ts'>
import { ref, 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 = {}) {
  let count: Ref<number> = ref(initialValue)
  
  const inc: () => void = () => {
    if(count.value < options.max) {
      count.value++
    } else {
      throw new Error(`最大加到${options.max}`)
    }
  }

  const dec: () => void = () => {
    if(count.value > options.min) {
      count.value--
    } else {
      throw new Error(`最小减到${options.min}`)
    }
  }

  const reset: () => void = () => {
    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>

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions