Skip to content

定制主题

Vital Design 通过 CSS 变量ConfigProvider 实现主题定制,支持全局主色、圆角、间距、字体等配置,并内置浅色 / 深色两套主题。

基础用法

在应用根节点使用 vd-config-provider,通过 theme-vars 传入需要覆盖的变量:

html
<vd-config-provider :theme-vars="themeVars">
  <vd-button type="primary">确认</vd-button>
</vd-config-provider>
ts
const themeVars = {
  common: {
    primary: '#07c160',
    'radius-md': '8px',
  },
  button: {
    height: '48px',
  },
};

theme-vars 为嵌套结构:common 写入 --vd-*,组件块(如 button)写入 --vd-{block}-theme-*。例如 common.primary--vd-primarybutton.height--vd-button-theme-height

完整可配置项见 ConfigProviderConfigProviderThemeVars 类型。

浅色 / 深色分别配置

当需要仅在某一主题下覆盖变量时,可使用 theme-vars-lighttheme-vars-dark

html
<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 组件会应用深色变量:

html
<vd-config-provider theme="dark">
  ...
</vd-config-provider>

跟随系统 / 手动切换

@vital-design/use 提供了 useDark,可读取本地缓存、系统主题或文档站主题偏好:

html
<vd-config-provider :theme="theme">
  ...
</vd-config-provider>
ts
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"> 中编写:

scss
.card {
  padding: $vd-padding-md;
  border-radius: $vd-radius-lg;
  background: $vd-background;
  color: $vd-color-text;
}

CSS 变量

也可在任意样式中直接引用:

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-navbarvd-tabbar 时,相关组件会自动参与高度计算,一般无需手动设置。

类型定义

ts
import type { ConfigProviderTheme, ConfigProviderThemeVars } from 'vital-design';

更多 API 见 ConfigProvider 组件文档

赣ICP备2025061025号-1