Skip to content

主题概述

N-UI 提供一套完整的运行时主题系统:通过 JSON 配置即可控制全局颜色、字体、圆角、间距、阴影等 Design Token,并内置默认、亮色、暗黑三套预设主题。

核心能力

  • JSON 配置主题:通过 ThemeConfig 对象完整定义所有 Token
  • 三套预设主题defaultlightdark
  • 运行时切换useTheme() composable 提供预设切换、自定义主题、暗黑模式切换
  • 后端加载:支持从远程接口异步加载主题 JSON
  • 持久化:自动保存当前主题到 localStorage,刷新后恢复

快速开始

在应用入口初始化

ts
import { createApp } from 'vue'
import { useTheme } from '@n-ui/hooks'
import App from './App.vue'

const app = createApp(App)
// useTheme 会在 onMounted 时自动恢复并应用上次保存的主题
app.mount('#app')
vue
<script setup lang="ts">
import { useTheme } from '@n-ui/hooks'

const { isDark, toggleDark, setTheme } = useTheme()
</script>

<template>
  <div>
    <button @click="setTheme('default')">默认主题</button>
    <button @click="setTheme('light')">亮色主题</button>
    <button @click="setTheme('dark')">暗黑主题</button>
    <button @click="toggleDark">
      {{ isDark ? '切换亮色' : '切换暗黑' }}
    </button>
  </div>
</template>

切换预设主题

ts
import { useTheme } from '@n-ui/hooks'

const { setTheme } = useTheme()

setTheme('default') // 默认蓝
setTheme('light')   // 靛蓝高亮
setTheme('dark')    // 暗黑

应用自定义主题

ts
import { useTheme } from '@n-ui/hooks'
import type { ThemeConfig } from '@n-ui/themes'

const { applyCustomTheme } = useTheme()

const myTheme: ThemeConfig = {
  name: 'brand',
  mode: 'light',
  colors: {
    primary: '#7c3aed',
    // ... 完整配置
  },
  // ...
}

applyCustomTheme(myTheme)

从后端加载主题

ts
import { useTheme } from '@n-ui/hooks'

const { loadTheme, isLoading, error } = useTheme()

async function fetchTheme() {
  await loadTheme('/api/theme/current')
}

导出当前主题

ts
import { useTheme } from '@n-ui/hooks'

const { exportTheme } = useTheme()

function downloadTheme() {
  const theme = exportTheme()
  const blob = new Blob([JSON.stringify(theme, null, 2)], { type: 'application/json' })
  // 触发下载 ...
}

设计原则

  1. 禁止硬编码颜色 - 所有颜色必须使用 CSS 变量
  2. 语义化命名 - 使用 --el-color-primary / --n-color-primary 等语义 Token
  3. 完整覆盖 - 亮色和暗色主题的 Token 完整覆盖
  4. 可扩展 - 业务可新增自定义 Token,并通过 applyCustomTheme 动态应用