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参数
| 参数名 | 类型 | 必填 | 说明 |
|---|---|---|---|
initialValue | number | 否 | 初始值,默认为 0 |
options | UseCounterOptions | 否 | 配置选项 |
deps | UseCounterDeps | 是 | 环境依赖 |
UseCounterOptions
| 属性名 | 类型 | 说明 |
|---|---|---|
min | number | 最小值限制 |
max | number | 最大值限制 |
返回值
| 属性名 | 类型 | 说明 |
|---|---|---|
count | Ref<number> | 当前计数值 |
inc | (delta?: number) => void | 增加(默认+1) |
dec | (delta?: number) => void | 减少(默认-1) |
reset | () => void | 重置到初始值 |
set | (val: number) => void | 设置指定值 |
工作原理
- 使用
ref创建响应式计数器 inc/dec方法修改计数,自动限制在min/max范围内reset恢复到初始值set设置值时也会进行范围限制- 所有操作都触发响应式更新
使用示例
基本用法
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 }
})