跳到主要内容

useDark

分类
导出大小
3.24 kB
上次更改
2 个月前
相关

具有自动数据持久化的响应式暗黑模式。

通过 Vue School 的免费视频课程学习 useDark!

演示

基本用法

ts
import { 
useDark
,
useToggle
} from '@vueuse/core'
const
isDark
=
useDark
()
const
toggleDark
=
useToggle
(
isDark
)

行为

useDarkusePreferredDarkuseStorage 结合使用。启动时,它会从 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
>

来源

源码演示文档

贡献者

Anthony Fu
wheat
Scott Bedard
IlyaL
SerKo
Robin
Anthony Fu
Teaghy
Waleed Khaled
Daniel Weaver
vaakian X
Kevin Cole
vaakian X
云游君
Mehran Mirshekaran
Máximo Mussini
Pig Fang
Alex Kozack
ordago
Le Minh Tri

更新日志

8c521 - feat(components)!: 重构组件并使其保持一致 (#4912)
0a9ed - feat!: 放弃对 Vue 2 的支持,优化打包并清理 (#4349)
v10.7.0
68688 - 修复:在 Vue 2.6 中 mode.system 未定义 (#3562)
v10.1.0
a1bef - 特性(useColorMode):将 state 暴露给 ref,弃用 emitAuto (#2980)

根据 MIT 许可证发布。