主题
useToggle
具有实用函数的布尔切换器。
🌐 A boolean switcher with utility functions.
示例
用法
🌐 Usage
ts
import { useToggle } from '@vueuse/core'
const [value, toggle] = useToggle()当你传入一个 ref 时,useToggle 将返回一个简单的切换函数:
🌐 When you pass a ref, useToggle will return a simple toggle function instead:
ts
import { useDark, useToggle } from '@vueuse/core'
const isDark = useDark()
const toggleDark = useToggle(isDark)切换功能
🌐 Toggle Function
切换功能可以通过两种方式调用:
🌐 The toggle function can be called in two ways:
ts
const [value, toggle] = useToggle()
toggle() // toggle between true and false
toggle(true) // set to specific value
// The toggle function returns the new value
const newValue = toggle() // returns the new value after toggling自定义值
🌐 Custom Values
你可以使用自定义的真值和假值来代替 true 和 false:
🌐 You can use custom truthy and falsy values instead of true and false:
ts
import { useToggle } from '@vueuse/core'
const [value, toggle] = useToggle('on', {
truthyValue: 'on',
falsyValue: 'off',
})
toggle() // 'off'
toggle() // 'on'自定义值也可以是响应式的:
🌐 The custom values can also be reactive:
ts
import { useToggle } from '@vueuse/core'
import { ref } from 'vue'
const truthy = ref('yes')
const falsy = ref('no')
const [value, toggle] = useToggle('yes', {
truthyValue: truthy,
falsyValue: falsy,
})小心
🌐 Caution
请注意,切换功能将第一个参数作为覆盖值。你可能需要避免在模板中直接将函数传递给事件,因为事件对象会被传入。
🌐 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 be passed in.
html
<!-- caution: $event will be passed in -->
<button @click="toggleDark" />
<!-- recommended to do this -->
<button @click="toggleDark()" />