useCounter计数器

发布时间:2024年01月10日

实现一个计数器

<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(initialValue)
  const inc = ()=>{
    if(options.max && count.value < options.max || !options.max ){
      count.value++
    }
  }
  const dec = ()=>{
    if(options.min && count.value > options.min || !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>

inc和dec函数内的校验也可以用以下方式实现:

  const inc = () => {
    if (Object.hasOwn(options, 'max') && count.value >= options.max) {
      return;
    }
    count.value++;
  }
  const dec = () => {
    if (Object.hasOwn(options, 'min') && count.value <= options.min) {
      return;
    }
    count.value--;
  }

文章来源:https://blog.csdn.net/content6/article/details/135512047
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。