Skip to content

useCounter

计数器Hook

前置依赖

依赖参数

参数名类型说明
deps.vue.ref<T>(value: T) => Ref<T>Vue的ref函数

环境要求

  • Vue 3: 使用Composition API
bash
npm install vue@^3.0.0

函数签名

typescript
interface UseCounterDeps {
  vue: {
    ref: <T>(value: T) => Ref<T>
  }
}

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

interface UseCounterReturn {
  count: Ref<number>
  inc: (delta?: number) => void
  dec: (delta?: number) => void
  reset: () => void
  set: (val: number) => void
}

function useCounter(
  initialValue?: number,
  options?: UseCounterOptions,
  deps: UseCounterDeps
): UseCounterReturn

参数

参数名类型必填说明
initialValuenumber初始值,默认为 0
optionsUseCounterOptions配置选项
depsUseCounterDeps环境依赖

UseCounterOptions

属性名类型说明
minnumber最小值限制
maxnumber最大值限制

返回值

属性名类型说明
countRef<number>当前计数值
inc(delta?: number) => void增加(默认+1)
dec(delta?: number) => void减少(默认-1)
reset() => void重置到初始值
set(val: number) => void设置指定值

工作原理

  1. 使用 ref 创建响应式计数器
  2. inc/dec 方法修改计数,自动限制在min/max范围内
  3. reset 恢复到初始值
  4. set 设置值时也会进行范围限制
  5. 所有操作都触发响应式更新

使用示例

基本用法

typescript
import { ref } from 'vue'
import { useCounter } from 'zcw-shared/hooks/useCounter'

const { count, inc, dec, reset } = useCounter(0, {}, {
  vue: { ref }
})

console.log(count.value) // 0
inc()                    // 1
inc(5)                   // 6
dec(2)                   // 4
reset()                  // 0

带范围限制

typescript
const { count, inc, dec } = useCounter(5, { min: 0, max: 10 }, {
  vue: { ref }
})

count.value // 5
inc(10)     // 10 (限制到max)
dec(20)     // 0  (限制到min)

购物车数量

vue
<script setup>
import { ref } from 'vue'
import { useCounter } from 'zcw-shared/hooks/useCounter'

const { count: quantity, inc, dec, set } = useCounter(1, { 
  min: 1, 
  max: 99 
}, { vue: { ref } })
</script>

<template>
  <div class="quantity-control">
    <button @click="dec" :disabled="quantity === 1">-</button>
    <input v-model.number="quantity" type="number" />
    <button @click="inc" :disabled="quantity === 99">+</button>
  </div>
</template>

分页控制

typescript
const { 
  count: currentPage, 
  inc: nextPage, 
  dec: prevPage 
} = useCounter(1, { min: 1, max: totalPages }, {
  vue: { ref }
})