Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

17 - 计数器 #2723

Open
Ly-TiR opened this issue May 17, 2024 · 0 comments
Open

17 - 计数器 #2723

Ly-TiR opened this issue May 17, 2024 · 0 comments

Comments

@Ly-TiR
Copy link

Ly-TiR commented May 17, 2024

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

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

/**
 * 实现计数器函数,确保功能正常工作
 * 1. 加 (+)
 * 2. 减 (-)
 * 3. 重置 
 * 4. 最小值 & 最大值 选项支持
*/

function useCounter(initialValue = 0, options: UseCounterOptions = {}) {
  let count = ref(initialValue)

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

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

  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>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant