定制主题
Vital Design 通过 CSS 变量 与 ConfigProvider 实现主题定制,支持全局主色、圆角、间距、字体等配置,并内置浅色 / 深色两套主题。
基础用法
在应用根节点使用 vd-config-provider,通过 theme-vars 传入需要覆盖的变量:
<vd-config-provider :theme-vars="themeVars">
<vd-button type="primary">确认</vd-button>
</vd-config-provider>const themeVars = {
common: {
primary: '#07c160',
'radius-md': '8px',
},
button: {
height: '48px',
},
};theme-vars 为嵌套结构:common 写入 --vd-*,组件块(如 button)写入 --vd-{block}-theme-*。例如 common.primary → --vd-primary,button.height → --vd-button-theme-height。
完整可配置项见 ConfigProvider 的 ConfigProviderThemeVars 类型。
浅色 / 深色分别配置
当需要仅在某一主题下覆盖变量时,可使用 theme-vars-light 与 theme-vars-dark:
<vd-config-provider
:theme="theme"
:theme-vars-light="lightVars"
:theme-vars-dark="darkVars"
>
...
</vd-config-provider>theme-vars:两种主题均生效的基础配置theme-vars-light:仅在theme="light"时合并theme-vars-dark:仅在theme="dark"时合并
开启深色模式
将 theme 设为 dark 即可开启深色模式,子树内所有 Vital Design 组件会应用深色变量:
<vd-config-provider theme="dark">
...
</vd-config-provider>跟随系统 / 手动切换
@vital-design/use 提供了 useDark,可读取本地缓存、系统主题或文档站主题偏好:
<vd-config-provider :theme="theme">
...
</vd-config-provider>import { computed } from 'vue';
import { useDark } from '@vital-design/use';
const { isDark, toggle } = useDark();
const theme = computed(() => (isDark.value ? 'dark' : 'light'));
// 手动切换
function switchTheme() {
toggle();
}useDark 会监听 uni.onThemeChange,在系统深浅色变化时自动更新。
常用主题变量
以下为常用的全局变量(完整列表见 packages/styles/variables/config.scss):
| 变量名 | 说明 | 默认值 |
|---|---|---|
common.primary | 品牌主色 | #1989fa |
common.success | 成功色 | #07c160 |
common.warning | 警告色 | #ff976a |
common.danger | 危险色 | #ee0a24 |
common.radius-sm ~ radius-xl | 圆角 | 2px ~ 16px |
common.padding-xs ~ padding-xl | 内边距 | 8px ~ 32px |
common.font-size-xs ~ font-size-xl | 字号 | 10px ~ 20px |
common.duration | 动画时长 | 0.3s |
在 Sass 中可直接使用对应 SCSS 变量,例如 $vd-primary、$vd-padding-md,其底层同样映射到 CSS 变量。
在样式中使用
SCSS 变量
项目已全局注入 @vital-design/styles 时,可在 .vue 的 <style lang="scss"> 中编写:
.card {
padding: $vd-padding-md;
border-radius: $vd-radius-lg;
background: $vd-background;
color: $vd-color-text;
}CSS 变量
也可在任意样式中直接引用:
.title {
color: var(--vd-primary);
font-size: var(--vd-font-size-lg);
}组件级 CSS 变量
部分组件除全局变量外,还提供组件私有 CSS 变量(如 Button、Badge 等),写在 theme-vars 对应组件键下,或通过组件 custom-style 覆盖。
布局相关变量
ConfigProvider 会自动注入以下布局变量,供 Navbar、Tabbar、Sticky、Fab 等组件计算偏移:
| CSS 变量 | 说明 |
|---|---|
--navbar-height | 导航栏高度 |
--tabbar-height | 标签栏高度 |
--status-bar-height | 状态栏高度 |
页面使用 vd-navbar、vd-tabbar 时,相关组件会自动参与高度计算,一般无需手动设置。
类型定义
import type { ConfigProviderTheme, ConfigProviderThemeVars } from 'vital-design';更多 API 见 ConfigProvider 组件文档。
