自定义主题
学习如何创建和使用自定义主题。
创建主题
定义主题配置
创建一个新的主题配置对象:
typescript
import type { ThemeConfig } from '@simple-blue/components';
export const myTheme: ThemeConfig = {
name: 'my-theme',
colors: {
primary: '#1890ff',
success: '#52c41a',
warning: '#faad14',
error: '#f5222d',
info: '#1890ff',
},
typography: {
fontFamily: '-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',
fontSize: {
xs: '12px',
sm: '14px',
base: '16px',
lg: '18px',
xl: '20px',
},
},
spacing: {
xs: '4px',
sm: '8px',
md: '16px',
lg: '24px',
xl: '32px',
},
};应用主题
typescript
import { ThemeManager } from '@simple-blue/components';
import { myTheme } from './theme';
const themeManager = ThemeManager.getInstance();
themeManager.setTheme(myTheme);主题配置项
colors
定义主题的色彩系统:
typescript
colors: {
primary: string; // 主色
success: string; // 成功色
warning: string; // 警告色
error: string; // 错误色
info: string; // 信息色
}typography
定义字体系统:
typescript
typography: {
fontFamily: string; // 字体族
fontSize: {
xs: string; // 最小字号
sm: string; // 小字号
base: string; // 基础字号
lg: string; // 大字号
xl: string; // 超大字号
};
}spacing
定义间距系统:
typescript
spacing: {
xs: string; // 最小间距
sm: string; // 小间距
md: string; // 标准间距
lg: string; // 大间距
xl: string; // 超大间距
}动态切换主题
可以在运行时动态切换主题:
vue
<template>
<div>
<a-select v-model:value="currentTheme" @change="handleThemeChange">
<a-select-option value="simple-blue">简约蓝</a-select-option>
<a-select-option value="custom">自定义</a-select-option>
</a-select>
</div>
</template>
<script setup lang="ts">
import { ref } from 'vue';
import { ThemeManager, simpleBlueTheme } from '@simple-blue/components';
import { myTheme } from './theme';
const currentTheme = ref('simple-blue');
const themeManager = ThemeManager.getInstance();
const handleThemeChange = (value: string) => {
if (value === 'simple-blue') {
themeManager.setTheme(simpleBlueTheme);
} else {
themeManager.setTheme(myTheme);
}
};
</script>覆盖 CSS 变量
如果只需要修改部分颜色,可以直接覆盖 CSS 变量:
css
:root {
--color-primary: #1890ff;
--color-success: #52c41a;
}或者在组件中动态修改:
vue
<template>
<div :style="themeStyle">
<!-- 组件内容 -->
</div>
</template>
<script setup lang="ts">
import { computed } from 'vue';
const themeStyle = computed(() => ({
'--color-primary': '#1890ff',
'--color-success': '#52c41a',
}));
</script>最佳实践
1. 保持一致性
确保主题配置与设计规范保持一致,避免随意修改。
2. 使用语义化命名
使用语义化的颜色命名(如 primary、success),而不是具体的颜色值(如 blue、green)。
3. 测试主题
在应用主题前,确保在不同场景下测试主题效果。
4. 文档化
为自定义主题编写文档,说明设计理念和使用场景。
示例:暗色主题
创建一个暗色主题:
typescript
export const darkTheme: ThemeConfig = {
name: 'dark',
colors: {
primary: '#177ddc',
success: '#49aa19',
warning: '#d89614',
error: '#d32029',
info: '#177ddc',
},
typography: {
fontFamily: '-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',
fontSize: {
xs: '12px',
sm: '14px',
base: '16px',
lg: '18px',
xl: '20px',
},
},
spacing: {
xs: '4px',
sm: '8px',
md: '16px',
lg: '24px',
xl: '32px',
},
};