useToggle
A boolean switcher with utility functions.
Demo
Value: OFF
Usage
js
import { useToggle } from '@vueuse/core'
const [value, toggle] = useToggle()
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)
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()" />
<!-- caution: $event will be pass in -->
<button @click="toggleDark" />
<!-- recommended to do this -->
<button @click="toggleDark()" />
Type Declarations
typescript
export interface UseToggleOptions<Truthy, Falsy> {
truthyValue?: MaybeComputedRef<Truthy>
falsyValue?: MaybeComputedRef<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>
): [Ref<T>, (value?: T) => T]
export interface UseToggleOptions<Truthy, Falsy> {
truthyValue?: MaybeComputedRef<Truthy>
falsyValue?: MaybeComputedRef<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>
): [Ref<T>, (value?: T) => T]
Source
Contributors
Anthony Fu
elky
Jelf
webfansplz
Alex Kozack
Alexey Iskhakov