入门

配置

配置颜色模式模块

你可以通过在 nuxt.config.ts 中提供 colorMode 属性来配置该模块。以下是默认选项:

nuxt.config.ts
export default defineNuxtConfig({
  modules: ['@nuxtjs/color-mode'],
  colorMode: {
    preference: 'system', // $colorMode.preference 的默认值
    fallback: 'light', // 未检测到系统偏好时的回退值
    globalName: '__NUXT_COLOR_MODE__',
    componentName: 'ColorScheme',
    classPrefix: '',
    classSuffix: '',
    storage: 'localStorage', // 或 'sessionStorage' 或 'cookie'
    storageKey: 'nuxt-color-mode',
    cookieAttrs: { maxAge: 31536000, path: '/' }
  }
})

选项

preference

  • 类型:string
  • 默认值:'system'

默认的颜色模式偏好。'system' 是一个特殊值,会根据系统偏好自动检测颜色模式。

fallback

  • 类型:string
  • 默认值:'light'

如果未检测到系统偏好,则使用的回退颜色模式值。

dataValue

  • 类型:string
  • 默认值:undefined

可选的数据集属性,添加到 <html> 元素上。例如,如果设置 dataValue: 'theme',则会在 <html> 上添加 data-theme="dark"。这对于使用 daisyUI 等库时非常有用。

storage

  • 类型:'localStorage' | 'sessionStorage' | 'cookie'
  • 默认值:'localStorage'

用于持久化颜色模式偏好的存储类型。

storageKey

  • 类型:string
  • 默认值:'nuxt-color-mode'

存储的键名。

cookieAttrs

  • 类型:object
  • 默认值:{ maxAge: 31536000, path: '/' }

storage 设置为 'cookie' 时,设置 cookie 的属性。默认情况下,cookie 设置为一年有效期并且作用域为根路径。

你可以覆盖这些属性以自定义 cookie 行为,例如设置 SameSiteSecure

nuxt.config.ts
export default defineNuxtConfig({
  modules: ['@nuxtjs/color-mode'],
  colorMode: {
    storage: 'cookie',
    cookieAttrs: {
      maxAge: 31536000,
      path: '/',
      sameSite: 'lax',
      secure: true,
    }
  }
})

在运行时覆盖 cookieAttrs

cookieAttrs 是通过 Nuxt 的公共运行时配置暴露的唯一选项;其他所有选项(包括 storage)都会在构建时固定。这意味着你可以无需重新构建,按部署分别更改 cookie 属性(最常见的是 domain),例如让同一个构建版本服务于多个主机。

你可以通过两种方式覆盖它。在这两种情况下,你的值都会深度合并到模块的 cookieAttrs 默认值(或你通过 colorMode.cookieAttrs 设置的值)之上,因此只需要指定要更改的属性——无需重复设置 maxAgepath 等属性。

nuxt.config 中通过 runtimeConfig

nuxt.config.ts
export default defineNuxtConfig({
  colorMode: {
    storage: 'cookie', // `storage` 仅在构建时生效,因此必须在此处设置
  },
  runtimeConfig: {
    public: {
      colorMode: {
        cookieAttrs: { domain: 'example.com' }, // 与 { maxAge: 31536000, path: '/' } 合并
      },
    },
  },
})

使用环境变量。 NUXT_PUBLIC_* 仅会覆盖启动时对象中已经存在的键——它们无法添加新键。因此,请先声明该属性(通过 colorMode.cookieAttrsruntimeConfig.public.colorMode.cookieAttrs),确保该键存在,然后再在运行时覆盖它:

nuxt.config.ts
colorMode: {
  storage: 'cookie',
  cookieAttrs: { domain: '' }, // 声明 `domain`,以便覆盖它
}
NUXT_PUBLIC_COLOR_MODE_COOKIE_ATTRS_DOMAIN=example.com node .output/server/index.mjs

由于 storage 在构建时固定,因此必须通过 colorMode.storage 选项启用 cookie 存储——在 runtimeConfig 中设置 storage 不会产生任何效果。