跳到内容

useDark

分类
导出大小
2.8 kB
最近更改
4个月前
相关

响应式暗黑模式,带自动数据持久化。

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

演示

基本用法

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

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

行为

useDark 结合了 usePreferredDarkuseStorage。启动时,它会从 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>

源码

源码演示文档

贡献者

Anthony Fu
wheat
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

更新日志

v12.0.0-beta.1 于 2024/11/21
0a9ed - feat!: drop Vue 2 support, optimize bundles and clean up (#4349)
v10.7.0 于 2023/12/5
68688 - fix: In Vue 2.6 mode.system is undefined (#3562)
v10.1.0 于 2023/4/22
a1bef - feat(useColorMode): expose state to the ref, deprecated emitAuto (#2980)
v10.0.0-beta.2 于 2023/3/28
d6d35 - feat: passthrough default handler from useColorSchema (#2866)

在 MIT 许可证下发布。