Loading source
Pulling the file list, source metadata, and syntax-aware rendering for this listing.
Source from repo
Apply VueUse composables in Vue 3/Nuxt projects to replace custom implementations with battle-tested utilities.
Files
Skill
Size
Entrypoint
Format
Open file
Syntax-highlighted preview of this file as included in the skill package.
references/useToggle.md
1---2category: Utilities3---45# useToggle67A boolean switcher with utility functions.89## Usage1011```ts12import { useToggle } from '@vueuse/core'1314const [value, toggle] = useToggle()15```1617When you pass a ref, `useToggle` will return a simple toggle function instead:1819```ts20import { useDark, useToggle } from '@vueuse/core'2122const isDark = useDark()23const toggleDark = useToggle(isDark)24```2526### Toggle Function2728The toggle function can be called in two ways:2930```ts31const [value, toggle] = useToggle()3233toggle() // toggle between true and false34toggle(true) // set to specific value3536// The toggle function returns the new value37const newValue = toggle() // returns the new value after toggling38```3940### Custom Values4142You can use custom truthy and falsy values instead of `true` and `false`:4344```ts45import { useToggle } from '@vueuse/core'4647const [value, toggle] = useToggle('on', {48truthyValue: 'on',49falsyValue: 'off',50})5152toggle() // 'off'53toggle() // 'on'54```5556The custom values can also be reactive:5758```ts59import { useToggle } from '@vueuse/core'60import { ref } from 'vue'6162const truthy = ref('yes')63const falsy = ref('no')6465const [value, toggle] = useToggle('yes', {66truthyValue: truthy,67falsyValue: falsy,68})69```7071## Caution7273Be 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 be passed in.7475```html76<!-- caution: $event will be passed in -->77<button @click="toggleDark" />78<!-- recommended to do this -->79<button @click="toggleDark()" />80```8182## Type Declarations8384```ts85export type ToggleFn = (value?: boolean) => void86export type UseToggleReturn = [ShallowRef<boolean>, ToggleFn] | ToggleFn87export interface UseToggleOptions<Truthy, Falsy> {88truthyValue?: MaybeRefOrGetter<Truthy>89falsyValue?: MaybeRefOrGetter<Falsy>90}91export declare function useToggle<Truthy, Falsy, T = Truthy | Falsy>(92initialValue: Ref<T>,93options?: UseToggleOptions<Truthy, Falsy>,94): (value?: T) => T95export declare function useToggle<96Truthy = true,97Falsy = false,98T = Truthy | Falsy,99>(100initialValue?: T,101options?: UseToggleOptions<Truthy, Falsy>,102): [ShallowRef<T>, (value?: T) => T]103```104