Skip to content

useToggle

Category
Export Size
224 B
Last Changed
last week

A boolean switcher with utility functions.

Demo

Value: OFF

Usage

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

const [value, toggle] = useToggle()

When you pass a ref, useToggle will return a simple toggle function instead:

js
import { useDark, useToggle } from '@vueuse/core'

const isDark = useDark()
const toggleDark = useToggle(isDark)

Note: be aware that the toggle function accepts the first argument as the override value. You might want to avoid directly passing the function to events in the template, as the event object will pass in.

html
<!-- caution: $event will be pass in -->
<button @click="toggleDark" />
<!-- recommended to do this -->
<button @click="toggleDark()" />

Type Declarations

typescript
type ToggleFn = (value?: boolean) => void
export type UseToggleReturn = [ShallowRef<boolean>, ToggleFn] | ToggleFn
export interface UseToggleOptions<Truthy, Falsy> {
  truthyValue?: MaybeRefOrGetter<Truthy>
  falsyValue?: MaybeRefOrGetter<Falsy>
}
export declare function useToggle<Truthy, Falsy, T = Truthy | Falsy>(
  initialValue: Ref<T>,
  options?: UseToggleOptions<Truthy, Falsy>,
): (value?: T) => T
export declare function useToggle<
  Truthy = true,
  Falsy = false,
  T = Truthy | Falsy,
>(
  initialValue?: T,
  options?: UseToggleOptions<Truthy, Falsy>,
): [ShallowRef<T>, (value?: T) => T]

Source

SourceDemoDocs

Contributors

Anthony Fu
Anthony Fu
IlyaL
Robin
elky
Jelf
webfansplz
Alex Kozack
Alexey Iskhakov

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.3.0 on
59f75 - feat(toValue): deprecate toValue from @vueuse/shared in favor of Vue's native
v12.0.0-beta.1 on
0a9ed - feat!: drop Vue 2 support, optimize bundles and clean up (#4349)
v10.0.0-beta.4 on
4d757 - feat(types)!: rename MaybeComputedRef to MaybeRefOrGetter
0a72b - feat(toValue): rename resolveUnref to toValue

Released under the MIT License.