Skip to content

useColorMode

具有自动数据持久性的反应式颜色模式(深色/浅色/自定义)。

¥Reactive color mode (dark / light / customs) with auto data persistence.

示例

← Click to change the color mode

基本用法

¥Basic Usage

js
import { useColorMode } from '@vueuse/core'

const mode = useColorMode() // Ref<'dark' | 'light'>

默认情况下,它将使用 usePreferredDark(又名 auto 模式)与用户的浏览器首选项进行匹配。读取 ref 时,默认情况下它将返回当前颜色模式(darklight 或你的自定义模式)。通过启用 emitAuto 选项,可以将 auto 模式包含在返回的模式中。当写入 ref 时,它将触发 DOM 更新并将颜色模式保留到本地存储(或你的自定义存储)。你可以通过 auto 设置回自动模式。

¥By default, it will match with users' browser preference using usePreferredDark (a.k.a auto mode). When reading the ref, it will by default return the current color mode (dark, light or your custom modes). The auto mode can be included in the returned modes by enabling the emitAuto option. When writing to the ref, it will trigger DOM updates and persist the color mode to local storage (or your custom storage). You can pass auto to set back to auto mode.

ts
mode.value // 'dark' | 'light'

mode.value = 'dark' // change to dark mode and persist

mode.value = 'auto' // change to auto mode

配置

¥Config

js
import { useColorMode } from '@vueuse/core'

const mode = useColorMode({
  attribute: 'theme',
  modes: {
    // custom colors
    dim: 'dim',
    cafe: 'cafe',
  },
}) // Ref<'dark' | 'light' | 'dim' | 'cafe'>

高级用法

¥Advanced Usage

你还可以显式访问系统首选项和 storaged 用户覆盖模式。

¥You can also explicit access to the system preference and storaged user override mode.

js
import { useColorMode } from '@vueuse/core'

const { system, store } = useColorMode()

system.value // 'dark' | 'light'
store.value // 'dark' | 'light' | 'auto'

const myColorMode = computed(() => store.value === 'auto' ? system.value : store.value)

组件用法

¥Component Usage

vue
<template>
  <UseColorMode v-slot="{ mode }">
    <button @click="mode = mode === 'dark' ? 'light' : 'dark'">
      Mode {{ mode }}
    </button>
  </UseColorMode>
</template>