Skip to content

useCounter

Category
Export Size
247 B
Last Changed
3 months ago

Basic counter with utility functions.

Demo

Count: 0

Basic Usage

js
import { useCounter } from '@vueuse/core'

const { count, inc, dec, set, reset } = useCounter()

Usage with options

js
import { useCounter } from '@vueuse/core'

const { count, inc, dec, set, reset } = useCounter(1, { min: 0, max: 16 })

Type Declarations

Show Type Declarations
typescript
export interface UseCounterOptions {
  min?: number
  max?: number
}
export interface UseCounterReturn {
  /**
   * The current value of the counter.
   */
  readonly count: Readonly<Ref<number>>
  /**
   * Increment the counter.
   *
   * @param {number} [delta=1] The number to increment.
   */
  inc: (delta?: number) => void
  /**
   * Decrement the counter.
   *
   * @param {number} [delta=1] The number to decrement.
   */
  dec: (delta?: number) => void
  /**
   * Get the current value of the counter.
   */
  get: () => number
  /**
   * Set the counter to a new value.
   *
   * @param val The new value of the counter.
   */
  set: (val: number) => void
  /**
   * Reset the counter to an initial value.
   */
  reset: (val?: number) => number
}
/**
 * Basic counter with utility functions.
 *
 * @see https://vueuse.org/useCounter
 * @param [initialValue]
 * @param options
 */
export declare function useCounter(
  initialValue?: MaybeRef<number>,
  options?: UseCounterOptions,
): {
  count: Readonly<
    | Ref<number, number>
    | ShallowRef<number, number>
    | WritableComputedRef<number, number>
  >
  inc: (delta?: number) => number
  dec: (delta?: number) => number
  get: () => number
  set: (val: number) => number
  reset: (val?: number) => number
}

Source

SourceDemoDocs

Contributors

Anthony Fu
IlyaL
Anthony Fu
Robin
Tycho
leewakin
Rock070
iChengbo
Damien Roche
Alex Kozack

Changelog

v13.1.0 on
c1d6e - feat(shared): ensure return types exists (#4659)
v12.8.0 on
7432f - feat(types): deprecate MaybeRef and MaybeRefOrGetter in favor of Vue's native (#4636)
v12.0.0-beta.1 on
0a9ed - feat!: drop Vue 2 support, optimize bundles and clean up (#4349)
v10.8.0 on
cf29c - fix: allow delta to be negative (#3650)
v10.3.0 on
6ae3a - feat: initialValue support ref (#3266)

Released under the MIT License.

Build faster with AI
New Masterclass to help you leverage AI in your Vue workflow.
Get Early Access