Skip to content

17 - 计数器 #2779

Closed
Closed
@wangqiJava

Description

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

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

const tempValue = ref<number>(0)

/**
 * Implement the composable function
 * Make sure the function works correctly
*/
function useCounter(initialValue = 0, options: UseCounterOptions = {}) {
  tempValue.value = initialValue

  const inc = ()=>{
    if(tempValue.value < options.max){
      tempValue.value++;
    }
  }

  const dec = ()=>{
    if(tempValue.value > options.min){
      tempValue.value--;
    }
  }

  const reset = ()=>{
    tempValue.value = initialValue
  }

  return {
    count:tempValue,
    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