useDark
响应式暗黑模式,带自动数据持久化。
通过 Vue School 的免费视频课程学习 useDark!演示
基本用法
js
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 favored dark mode,当类 dark
应用于 html
标签时,这将启用暗黑模式,例如
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: boolean) {
// update the dom, call the API or something
},
})
js
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>
类型声明
typescript
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>