useDark
具有自动数据持久化的响应式暗黑模式。
通过 Vue School 的免费视频课程学习 useDark!演示
基本用法
ts
import { useDark, useToggle } from '@vueuse/core'
const isDark = useDark()
const toggleDark = useToggle(isDark)行为
useDark 与 usePreferredDark 和 useStorage 结合使用。启动时,它会从 localStorage/sessionStorage(键可配置)读取值,查看是否有用户配置的颜色方案,如果没有,它将使用用户的系统偏好设置。当您更改 isDark ref 时,它将更新相应元素的属性,然后将偏好设置存储到存储(默认键:vueuse-color-scheme)以进行持久化。
请注意,
useDark只处理 DOM 属性更改,以便您在 CSS 中应用正确的选择器。它不处理实际的样式、主题或 CSS。
配置
默认情况下,它使用 Tailwind CSS 青睐的暗黑模式,当 html 标签上应用 dark 类时,例如
html
<!--light-->
<html>
...
</html>
<!--dark-->
<html class="dark">
...
</html>不过,您也可以自定义它,使其与大多数 CSS 框架配合使用。
例如
ts
const isDark = useDark({
selector: 'body',
attribute: 'color-scheme',
valueDark: 'dark',
valueLight: 'light',
})将如下工作
html
<!--light-->
<html>
<body color-scheme="light">
...
</body>
</html>
<!--dark-->
<html>
<body color-scheme="dark">
...
</body>
</html>如果上述配置仍不符合您的需求,您可以使用 onChanged 选项完全控制如何处理更新。
ts
const isDark = useDark({
onChanged(dark) {
// update the dom, call the API or something
},
})组件用法
此函数还通过
@vueuse/components包提供了一个无渲染组件版本。了解更多用法。
vue
<template>
<UseDark v-slot="{ isDark, toggleDark }">
<button @click="toggleDark()">
Is Dark: {{ isDark }}
</button>
</UseDark>
</template>类型声明
ts
export interface UseDarkOptions
extends Omit<UseColorModeOptions<BasicColorSchema>, "modes" | "onChanged"> {
/**
* Value applying to the target element when isDark=true
*
* @default 'dark'
*/
valueDark?: string
/**
* Value applying to the target element when isDark=false
*
* @default ''
*/
valueLight?: string
/**
* A custom handler for handle the updates.
* When specified, the default behavior will be overridden.
*
* @default undefined
*/
onChanged?: (
isDark: boolean,
defaultHandler: (mode: BasicColorSchema) => void,
mode: BasicColorSchema,
) => void
}
/**
* Reactive dark mode with auto data persistence.
*
* @see https://vueuse.org.cn/useDark
* @param options
*/
export declare function useDark(
options?: UseDarkOptions,
): WritableComputedRef<boolean, boolean>
export type UseDarkReturn = ReturnType<typeof useDark>