主题
useDark
具有自动数据持久性的反应式夜间模式。
🌐 Reactive dark mode with auto data persistence.
通过 Vue School 的免费视频课程学习 useDark!示例
基本用法
🌐 Basic Usage
ts
import { useDark, useToggle } from '@vueuse/core'
const isDark = useDark()
const toggleDark = useToggle(isDark)行为
🌐 Behavior
useDark 与 usePreferredDark 和 useStorage 结合使用。启动时,它会从 localStorage/sessionStorage 中读取值(键可配置),以查看是否有用户配置的配色方案,如果没有,它将使用用户的系统偏好。当你更改 isDark 引用时,它会更新相应元素的属性,然后将偏好存储到存储中(默认键:vueuse-color-scheme)以保持持久性。
请注意,
useDark仅处理 DOM 属性的更改,以便你在 CSS 中应用适当的选择器。它不会为你处理实际的样式、主题或 CSS。
配置
🌐 Configuration
默认情况下,它使用Tailwind CSS 推荐的夜间模式,当在 html 标签上应用类 dark 时会启用夜间模式,例如:
🌐 By default, it uses Tailwind CSS favored dark mode, which enables dark mode when class dark is applied to the html tag, for example:
html
<!--light-->
<html>
...
</html>
<!--dark-->
<html class="dark">
...
</html>不过,你还可以对其进行自定义,使其与大多数 CSS 框架兼容。
🌐 Still, you can also customize it to make it work with most CSS frameworks.
例如:
🌐 For example:
ts
const isDark = useDark({
selector: 'body',
attribute: 'color-scheme',
valueDark: 'dark',
valueLight: 'light',
})会像
🌐 will work like
html
<!--light-->
<html>
<body color-scheme="light">
...
</body>
</html>
<!--dark-->
<html>
<body color-scheme="dark">
...
</body>
</html>如果上述配置仍然无法满足你的需求,你可以使用onChanged选项完全掌控如何处理更新。
🌐 If the configuration above still does not fit your needs, you can use theonChanged option to take full control over how you handle updates.
ts
const isDark = useDark({
onChanged(dark) {
// update the dom, call the API or something
},
})组件用法
🌐 Component Usage
vue
<template>
<UseDark v-slot="{ isDark, toggleDark }">
<button @click="toggleDark()">
Is Dark: {{ isDark }}
</button>
</UseDark>
</template>