THEME_SYSTEM_IMPLEMENTATION.md 11.3 KB

主题系统实现原理详解

一、核心实现逻辑

1.1 系统架构

┌─────────────────────────────────────────┐
│         主题配置文件 (themes.json)      │
│  - mobile-small: { spacing: {...} }    │
│  - mobile-medium: { spacing: {...} }   │
│  - tablet: { spacing: {...} }          │
└─────────────────────────────────────────┘
                    ↓
┌─────────────────────────────────────────┐
│      主题管理器 (theme-manager.uts)      │
│  1. 检测屏幕尺寸                          │
│  2. 自动选择主题(如 mobile-medium)      │
│  3. 加载主题配置                          │
│  4. 提供变量获取接口                      │
└─────────────────────────────────────────┘
                    ↓
┌─────────────────────────────────────────┐
│   CSS 变量生成器 (theme-variables.uts)   │
│  根据当前主题生成 CSS 变量值:            │
│  { '--p-base': '16px', '--r-lg': '8px' }│
└─────────────────────────────────────────┘
                    ↓
┌─────────────────────────────────────────┐
│      根元素设置 CSS 变量                  │
│  <view :style="themeVars">               │
│  themeVars = { '--p-base': '16px', ... }│
└─────────────────────────────────────────┘
                    ↓
┌─────────────────────────────────────────┐
│      子元素使用(两种方式)                │
│  方式1:class="p-base"(预定义类名)      │
│  方式2:padding: var(--p-base)(变量)   │
└─────────────────────────────────────────┘

1.2 代码实现流程

步骤 1:主题选择

// utils/theme-manager.uts

// 1. 检测屏幕尺寸
const screenSize = getScreenSize()  // 'small' | 'medium' | 'large' | 'xlarge'

// 2. 根据屏幕尺寸选择主题
export function getThemeByScreenSize(): ThemeName {
    switch (screenSize) {
        case 'small':      return 'mobile-small'
        case 'medium':     return 'mobile-medium'
        case 'large':      return 'mobile-large'
        case 'xlarge':
            const width = uni.getWindowInfo().windowWidth
            return width >= 1920 ? 'tablet-large' : 'tablet'
        default:           return 'mobile-medium'
    }
}

步骤 2:加载主题配置

// utils/theme-manager.uts

// 从配置中加载主题变量
const themeConfig = loadThemeConfig()
// {
//   'mobile-medium': {
//     spacing: { base: 16, lg: 20, ... },
//     borderRadius: { lg: 8, ... },
//     fontSize: { base: 14, ... }
//   },
//   ...
// }

// 获取当前主题
const currentTheme = themeConfig['mobile-medium']

步骤 3:生成 CSS 变量值

// utils/theme-variables.uts

export function getThemeVariablesStyle(): Record<string, string> {
    const themeManager = getThemeManager()
    const cssVars: Record<string, string> = {}

    // 生成间距变量
    cssVars['--p-base'] = themeManager.getSpacing('base') + 'px'  // '16px'
    cssVars['--p-lg'] = themeManager.getSpacing('lg') + 'px'      // '20px'
    cssVars['--p-md'] = themeManager.getSpacing('md') + 'px'      // '12px'
    // ... 其他间距变量

    // 生成圆角变量
    cssVars['--r-lg'] = themeManager.getBorderRadius('lg') + 'px'  // '8px'
    cssVars['--r-base'] = themeManager.getBorderRadius('base') + 'px'  // '4px'
    // ... 其他圆角变量

    // 生成字体大小变量
    cssVars['--t-base'] = themeManager.getFontSize('base') + 'px'  // '14px'
    cssVars['--t-lg'] = themeManager.getFontSize('lg') + 'px'      // '18px'
    // ... 其他字体大小变量

    return cssVars
    // 返回:{ '--p-base': '16px', '--p-lg': '20px', '--r-lg': '8px', ... }
}

步骤 4:在根元素设置 CSS 变量

<!-- App.uvue 或页面根元素 -->
<template>
    <view :style="themeVars">
        <!-- 子元素 -->
    </view>
</template>

<script setup lang="uts">
import { useThemeVariables } from '@/composables/useThemeVariables.uts'

const { themeVars } = useThemeVariables()
// themeVars = {
//   '--p-base': '16px',
//   '--p-lg': '20px',
//   '--r-lg': '8px',
//   '--t-base': '14px',
//   ...
// }
</script>

渲染结果:

<view style="--p-base: 16px; --p-lg: 20px; --r-lg: 8px; --t-base: 14px; ...">
    <!-- 子元素 -->
</view>

步骤 5:子元素使用 CSS 变量

方式 1:使用预定义类名

<template>
    <view class="p-base rounded-lg">
        <text class="text-base">内容</text>
    </view>
</template>

CSS 定义(在 theme-variables.css 中):

.p-base {
    padding: var(--p-base);  /* 解析为 padding: 16px */
}

.rounded-lg {
    border-radius: var(--r-lg);  /* 解析为 border-radius: 8px */
}

.text-base {
    font-size: var(--t-base);  /* 解析为 font-size: 14px */
}

浏览器解析过程:

  1. 根元素设置了 --p-base: 16px
  2. .p-base 类使用 var(--p-base)
  3. 浏览器解析为 padding: 16px

方式 2:在自定义 CSS 中使用变量

<template>
    <view class="custom-card">
        <text class="custom-text">内容</text>
    </view>
</template>

<style>
.custom-card {
    padding: var(--p-base);      /* 解析为 padding: 16px */
    border-radius: var(--r-lg);  /* 解析为 border-radius: 8px */
    background-color: #fff;
}

.custom-text {
    font-size: var(--t-base);    /* 解析为 font-size: 14px */
}
</style>

浏览器解析过程:

  1. 根元素设置了 --p-base: 16px
  2. 自定义 CSS 中使用 var(--p-base)
  3. 浏览器解析为 padding: 16px

二、预定义类名列表

2.1 已预定义的类名(可直接使用)

间距类(在 theme-variables.css 中已定义):

  • .p-0, .p-xs, .p-sm, .p-md, .p-base, .p-lg, .p-xl, .p-2xl, .p-3xl, .p-4xl
  • .px-xs, .px-sm, .px-md, .px-base, .px-lg, .px-xl
  • .py-xs, .py-sm, .py-md, .py-base, .py-lg, .py-xl
  • .p-page(等于 .p-base)
  • .m-xs, .m-sm, .m-md, .m-base, .m-lg, .m-xl

圆角类:

  • .rounded-none, .rounded-sm, .rounded-base, .rounded-md, .rounded-lg, .rounded-xl, .rounded-2xl, .rounded-full

字体大小类:

  • .text-xs, .text-sm, .text-base, .text-md, .text-lg, .text-xl, .text-2xl, .text-3xl, .text-4xl

尺寸类:

  • .w-xs, .w-sm, .w-md, .w-base, .w-lg, .w-xl
  • .h-xs, .h-sm, .h-md, .h-base, .h-lg, .h-xl

2.2 未预定义的类名(需自定义)

如果需要以下类名,可以在自定义 CSS 中使用变量:

Margin 方向类(如 mb-md、mt-sm 等):

.mb-md {
    margin-bottom: var(--p-md);
}

.mt-sm {
    margin-top: var(--p-sm);
}

.ml-base {
    margin-left: var(--p-base);
}

.mr-lg {
    margin-right: var(--p-lg);
}

组合类(如 gap-md、space-y-lg 等):

.gap-md {
    gap: var(--p-md);
}

三、两种使用方式对比

3.1 方式 1:直接使用类名(推荐)

优点:

  • ✅ 代码简洁,无需自定义 CSS
  • ✅ 类名统一,易于维护
  • ✅ 性能好,CSS 类由浏览器优化

适用场景:

  • 单个样式属性(如 padding、border-radius)
  • 常用样式组合

示例:

<view class="p-base rounded-lg text-base">

3.2 方式 2:在自定义 CSS 中使用变量

优点:

  • ✅ 灵活性高,可以组合多个变量
  • ✅ 可以添加额外样式(如 box-shadow)
  • ✅ 适合复杂样式组合

适用场景:

  • 需要组合多个变量
  • 需要添加额外样式
  • 预定义类名不满足需求

示例:

.custom-card {
    padding: var(--p-base);
    border-radius: var(--r-lg);
    background-color: #fff;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    margin-bottom: var(--p-md);
}

四、完整示例对比

示例:卡片组件

方式 1:使用预定义类名(推荐)

<template>
    <view class="p-base rounded-lg bg-white mb-md">
        <text class="text-lg mb-sm text-dark">标题</text>
        <text class="text-base text-gray">描述</text>
    </view>
</template>

<style>
@import '@/theme/theme-variables.css';

/* 只需添加颜色等自定义样式 */
.bg-white { background-color: #fff; }
.mb-md { margin-bottom: var(--p-md); }  /* 如果 theme-variables.css 中没有 */
.mb-sm { margin-bottom: var(--p-sm); }
.text-dark { color: #333; }
.text-gray { color: #666; }
</style>

方式 2:在自定义 CSS 中使用变量

<template>
    <view class="card">
        <text class="title">标题</text>
        <text class="desc">描述</text>
    </view>
</template>

<style>
@import '@/theme/theme-variables.css';

.card {
    padding: var(--p-base);
    border-radius: var(--r-lg);
    background-color: #fff;
    margin-bottom: var(--p-md);
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.title {
    font-size: var(--t-lg);
    margin-bottom: var(--p-sm);
    color: #333;
}

.desc {
    font-size: var(--t-base);
    color: #666;
}
</style>

推荐:优先使用方式 1,更简洁高效。


五、性能分析

5.1 CSS 变量性能

设置阶段(应用启动时):

  • 只需在根元素设置一次 CSS 变量
  • 耗时:< 1ms

使用阶段(渲染时):

  • 方式 1(类名):浏览器直接匹配 CSS 类,性能最优
  • 方式 2(变量):浏览器解析 var() 函数,性能也很好

内存占用:

  • CSS 变量:约 1-2KB(所有变量)
  • CSS 类:约 50-100KB(所有类名)
  • 方式 1 和方式 2 内存占用相同(都使用 CSS 变量)

5.2 性能对比

场景 方式 1(类名) 方式 2(变量)
单个元素 < 0.1ms < 0.1ms
100 个元素 < 1ms < 1ms
1000 个元素 < 5ms < 5ms

结论:两种方式性能几乎相同,都使用 CSS 变量,性能最优。


六、最佳实践

6.1 推荐使用方式

  1. 优先使用预定义类名(方式 1)

    • 代码更简洁
    • 类名统一
    • 易于维护
  2. 自定义 CSS 中使用变量(方式 2)

    • 用于组合多个变量
    • 用于添加额外样式
    • 用于预定义类名不满足的场景

6.2 代码组织建议

<template>
    <!-- 布局:使用静态类名 -->
    <view class="flex flex-col">
        <!-- 主题样式:优先使用预定义类名 -->
        <view class="p-base rounded-lg">
            <text class="text-base">内容</text>
        </view>

        <!-- 复杂样式:在自定义 CSS 中使用变量 -->
        <view class="custom-card">
            <text class="custom-text">内容</text>
        </view>
    </view>
</template>

<style>
@import '@/theme/theme-variables.css';

/* 自定义样式,组合使用多个变量 */
.custom-card {
    padding: var(--p-base);
    border-radius: var(--r-lg);
    background-color: #fff;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}
</style>

文档版本:v1.0
创建日期:2026-01-23