Skip to content

useToggle

Category
Export Size
200 B
Last Changed
last month

一个带有实用功能的布尔切换器。

Demo

值:关

用法

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

const [value, toggle] = useToggle()

当你传入一个 ref 时,useToggle 将返回一个简单的切换函数:

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

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

注意:请注意,切换函数接受第一个参数作为覆盖值。您可能希望避免直接将函数传递给模板中的事件,因为事件对象将被传入。

html
<!-- 注意:$event 将被传入 -->
<button @click="toggleDark" />
<!-- 推荐这样做 -->
<button @click="toggleDark()" />

类型声明

typescript
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>,
): [Ref<T>, (value?: T) => T]

Source

SourceDemoDocs

贡献者

Anthony Fu
丶远方
Anthony Fu
elky
Jelf
webfansplz
Alex Kozack
Alexey Iskhakov

变更日志

v10.0.0-beta.4 on 4/13/2023
4d757 - feat(types)!: rename MaybeComputedRef to MaybeRefOrGetter
0a72b - feat(toValue): rename resolveUnref to toValue

Released under the MIT License.