useTheme — Theming
17:43Description
useTheme manages themes and dark mode: after a switch the palette syncs to $u.color and CSS variables in real time, and the theme and dark-mode settings are persisted to local storage.
Examples
Current theme state
Shows the currentTheme name, the darkMode setting, the mode resolved by isInDarkMode() and the number of entries in themes.
View source
<template>
<ux-cell-group :border="false">
<ux-cell-item
v-for="(item, index) in stateRows"
:key="index"
:title="item.desc"
:value="item.result"
:arrow="false"
:border-bottom="!item.last"
/>
</ux-cell-group>
</template>
<script setup lang="ts">
import { useTheme } from '@/uni_modules/uview-pro-x';
// 解构方式使用:const { currentTheme } = useTheme()
const { themes, currentTheme, darkMode, isInDarkMode } = useTheme();
type Row = {
desc: string;
result: string;
last: boolean;
};
const stateRows = computed((): Row[] => {
const theme = currentTheme.value;
return [
{ desc: '当前主题:', result: theme != null ? theme.name : '-', last: false },
{ desc: '暗黑设置:', result: darkMode.value, last: false },
{ desc: '生效暗黑:', result: isInDarkMode() ? 'dark' : 'light', last: false },
{ desc: '可用主题数:', result: themes.value.length.toString(), last: true }
];
});
</script>Theme switching
initTheme registers two demo themes (the list itself is the final theme list; built-in themes only serve as the baseline for same-name items), and tapping a cell calls setTheme to switch and persist.
View source
<template>
<ux-cell-group :border="false">
<ux-cell-item
v-for="(item, index) in themeRows"
:key="index"
:title="item.label"
:label="item.name"
:value="item.active ? '当前' : ''"
:arrow="true"
:border-bottom="!item.last"
@click="setTheme(item.name)"
/>
</ux-cell-group>
</template>
<script setup lang="ts">
import { $u, useTheme, type Theme, type ThemeColor } from '@/uni_modules/uview-pro-x';
const { themes, currentTheme, initTheme, setTheme } = useTheme();
type ThemeRow = {
name: string;
label: string;
primary: string;
active: boolean;
last: boolean;
};
// 演示主题:只声明主色,其余令牌由内置基线同名项补齐
function buildDemoTheme(name: string, label: string, primary: string): Theme {
const palette: ThemeColor = { primary: primary };
const theme: Theme = { name: name, label: label, color: palette };
return theme;
}
// 传入的非空列表就是最终主题列表,内置主题不再自动追加,只作同名项的基线
initTheme([buildDemoTheme('demoPurple', '演示紫', '#7c4dff'), buildDemoTheme('demoGreen', '演示绿', '#00b578')]);
const themeRows = computed((): ThemeRow[] => {
const list = themes.value;
const current = currentTheme.value;
const currentName = current != null ? current.name : '';
const rows: ThemeRow[] = [];
for (let i = 0; i < list.length; i++) {
const item = list[i];
rows.push({
name: item.name,
label: $u.strOr(item.label, item.name),
primary: $u.strOr(item.color.primary, ''),
active: item.name == currentName,
last: i == list.length - 1
});
}
return rows;
});
</script>Dark mode
setDarkMode accepts light / dark / auto, while toggleDarkMode flips between dark and light.
View source
<template>
<ux-row :gutter="10">
<ux-col :span="4">
<ux-button size="small" type="primary" block text="亮色" @click="setDarkMode('light')" />
</ux-col>
<ux-col :span="4">
<ux-button size="small" type="info" block text="暗黑" @click="setDarkMode('dark')" />
</ux-col>
<ux-col :span="4">
<ux-button size="small" type="info" block text="跟随系统" @click="setDarkMode('auto')" />
</ux-col>
</ux-row>
<ux-gap :height="10" />
<ux-button size="small" type="warning" block text="切换明暗" @click="toggleDarkMode()" />
</template>
<script setup lang="ts">
import { useTheme } from '@/uni_modules/uview-pro-x';
const { darkMode, setDarkMode, toggleDarkMode } = useTheme();
// light 强制亮色 / dark 强制暗黑 / auto 跟随系统
const isLight = computed((): boolean => darkMode.value == 'light');
</script>Theme CSS variables
Reads the current values of --u-theme-mode, --u-type-primary, --u-type-success and --u-main-color from cssVars.
View source
<template>
<ux-cell-group :border="false">
<ux-cell-item
v-for="(item, index) in cssVarRows"
:key="index"
:title="item.desc"
:value="item.result"
:arrow="false"
:border-bottom="!item.last"
/>
</ux-cell-group>
</template>
<script setup lang="ts">
import { useTheme } from '@/uni_modules/uview-pro-x';
const { cssVars } = useTheme();
type Row = {
desc: string;
result: string;
last: boolean;
};
// 变量表整体替换,computed 会跟随刷新;config.type 内的令牌会加 --u-type 前缀
function cssVar(key: string): string {
const value = cssVars.value[key];
if (value == null) return '-';
return value.toString();
}
const cssVarRows = computed((): Row[] => [
{ desc: '--u-theme-mode', result: cssVar('--u-theme-mode'), last: false },
{ desc: '--u-type-primary', result: cssVar('--u-type-primary'), last: false },
{ desc: '--u-type-success', result: cssVar('--u-type-success'), last: false },
{ desc: '--u-main-color', result: cssVar('--u-main-color'), last: true }
]);
</script>Restore default
initTheme() without arguments returns to the built-in theme and sets darkMode to light, and the same reset runs when leaving the page.
View source
<template>
<ux-button size="small" type="primary" block text="恢复默认主题" @click="restoreDefault()" />
</template>
<script setup lang="ts">
import { useTheme } from '@/uni_modules/uview-pro-x';
const { currentTheme, initTheme, setTheme, setDarkMode } = useTheme();
// 无参 initTheme() 回到内置主题;再把解析后的主题名写回存储
function restoreDefault(): void {
initTheme();
setDarkMode('light');
const current = currentTheme.value;
if (current != null) setTheme(current.name);
}
// 离开页面也恢复,避免影响其他页面
onUnload((): void => {
restoreDefault();
});
</script>Usage
Highlights that theme state is shared at module level, setTheme / setDarkMode write to local storage, and extra themes are injected through initTheme([...]).
View source
<template>
<ux-alert-tips type="primary" :show-icon="true" title="const { themes, currentTheme, setTheme } = useTheme()" />
<ux-gap :height="8" />
<ux-alert-tips type="primary" :show-icon="true" title="状态为模块级,跨页面共享同一份主题" />
<ux-gap :height="8" />
<ux-alert-tips type="primary" :show-icon="true" title="setTheme / setDarkMode 会写入本地存储" />
<ux-gap :height="8" />
<ux-alert-tips type="primary" :show-icon="true" title="initTheme([...]) 的列表即主题列表,内置主题只作同名项基线" />
</template>
<script setup lang="ts">
import { useTheme } from '@/uni_modules/uview-pro-x';
const { themes, currentTheme, cssVars, setTheme, setDarkMode, initTheme } = useTheme();
</script>API
Parameters
| Parameter | Description | Type | Default | Version |
|---|---|---|---|---|
| - | This hook takes no arguments | - | - | - |
Returns
| Field | Description | Type |
|---|---|---|
| themes | Available themes (the passed list itself when provided; built-in themes only serve as the baseline for same-name items) | Ref<Theme[]> |
| currentTheme | Active theme | Ref<Theme | null> |
| darkMode | Dark-mode setting: auto / light / dark | Ref<DarkMode> |
| cssVars | CSS variable table for the active mode, including --u-theme-mode and -rgb variants | Ref<JsonObject> |
| initTheme | Initializes themes; without arguments it returns to built-in themes, with a list that list becomes the final theme list | (theme?: UViewProXThemeOptions | null) => void |
| setTheme | Switches and persists the theme; returns immediately when the theme is not registered | (themeName: string) => void |
| getAvailableThemes | Returns a copy of the available theme list | () => Theme[] |
| getCurrentTheme | Returns the active theme | () => Theme | null |
| setDarkMode | Sets and persists the dark mode, then re-applies the theme immediately | (mode: DarkMode) => void |
| getDarkMode | Returns the current dark-mode setting | () => DarkMode |
| isInDarkMode | Resolves whether dark mode is active under the current setting | () => boolean |
| toggleDarkMode | Toggles between dark and light | () => void |
Notes
autofollows the system: on App it listens touni.onOsThemeChangeinside#ifdef APP, on other platforms it listens touni.onHostThemeChangeinside#ifndef APP, and the theme is re-applied only whiledarkModeisauto.setDarkModecallsuni.setAppTheme(wrapped in#ifdef APP) so the native page background and navigation bar follow the mode; this call has no effect outside App.setTheme/setDarkModeboth write to local storage and apply immediately;setThemereturns without switching when the given theme name is not registered.initThemewithout arguments returns to the built-in theme; a non-empty theme list becomes the final theme list, built-in themes are no longer appended but only serve as the baseline for same-name items (nameequal toBASE_THEME_NAME); to keep the default theme, declare{ name: BASE_THEME_NAME, color: {} }explicitly in the list. Within the list, a later item with the same name overrides the earlier one.- Dark mode defaults to
'light'(i.e.config.defaultDarkMode) and does not follow the system unless configured; set it to'auto'explicitly (defaultDarkMode: 'auto'at install time, orsetDarkMode('auto')at runtime). - The single-theme shape (passing a
ThemeColordirectly) has nodarkColor/css/darkCssfield, so the dark palette is always derived from the light tokens; switch to the array shape — even with a single theme — when you need precise dark colors. - Theme entries with an empty or missing
nameare dropped (no implicit fallback); override the built-in theme by declaring it explicitly with theBASE_THEME_NAMEconstant.