SwThemeSwitch

SwThemeSwitch 是内置主题切换器:由 useTheme() 驱动,点击在「跟随系统 / 浅色 / 深色」之间切换。

自 gate:组件只在 swift.config.json 的 theme.mode: 'toggle' 时渲染切换按钮;system / dark / light(无手动切换语义)三种模式下渲染为空。所以消费方模板里直接放 <SwThemeSwitch /> 即可——改 theme.mode 配置,切换器自动出现 / 消失,无需写条件判断。

切换形态跟随 theme.toggleStates:

  • 3 态(默认):图标随 theme,点击 auto → light → dark → auto 循环,可回到「跟随系统」。
  • 2 态:图标随 resolvedTheme(当前实际明暗),点击仅 light ↔ dark,切换后无法回到跟随系统。

定制能力三档(headless 逃生舱)

按「改多少」从轻到重:

  1. 换皮肤 —— --sw-theme-switch-* CSS token(尺寸 / 颜色 / 背景 / 圆角 / hover)。
  2. 换图标 —— #light / #dark / #auto 具名插槽传自己图标库的图标(仅默认单按钮 UI 生效)。
  3. 换整个交互 —— 默认作用域插槽:传了就完全自渲染 UI,组件把 { theme, resolvedTheme, mode, toggleStates, toggleTheme, setTheme, canSwitch } 交给你,同时仍复用自 gate(mode !== 'toggle' 时整体渲染空,你不用自己判断)。

想完全脱离本组件自建也行:useTheme() 是公开 composable,可直接读写主题。

基础用法

默认切换器(本文档站为 toggle 模式,点击真实切换主题)

加载中...
<template>
  <!-- 只在 theme.mode: 'toggle' 时渲染;其它模式自动为空 -->
  <SwThemeSwitch />
</template>

换图标(具名插槽)

#light / #dark / #auto 覆盖默认内联 SVG,换成消费方图标库的图标(作用域 { theme, resolved }):

用 @phosphor-icons/vue 替换默认图标

加载中...
<script setup lang="ts">
import { PhSun, PhMoon, PhCircleHalf } from '@phosphor-icons/vue'
</script>

<template>
  <SwThemeSwitch>
    <template #light><PhSun :size="18" /></template>
    <template #dark><PhMoon :size="18" /></template>
    <template #auto><PhCircleHalf :size="18" /></template>
  </SwThemeSwitch>
</template>

自渲染整个 UI(默认作用域插槽)

传默认作用域插槽即接管整个切换器 UI,复用 framework 的数据 + 动作 + 自 gate。这里用三个按钮做「跟随系统 / 浅色 / 深色」三选一:

默认作用域插槽自渲染(setTheme 三选一)

加载中...
<template>
  <SwThemeSwitch v-slot="{ theme, resolvedTheme, setTheme }">
    <SwButton :class="{ 'is-active': theme === 'auto' }" @click="setTheme('auto')">跟随系统</SwButton>
    <SwButton :class="{ 'is-active': theme === 'light' }" @click="setTheme('light')">浅色</SwButton>
    <SwButton :class="{ 'is-active': theme === 'dark' }" @click="setTheme('dark')">深色</SwButton>
    <span>实际明暗:{{ resolvedTheme }}</span>
  </SwThemeSwitch>
</template>

Props

名称类型必填默认值说明
sizenumber18默认内联图标尺寸(px)。用默认作用域插槽自渲染时不生效。⚠️ 与 SwTable 的 size('default' | 'compact' 密度枚举)不同,这里是像素数值

Slots

名称作用域参数说明
default{ theme, resolvedTheme, mode, toggleStates, toggleTheme, setTheme, canSwitch }自渲染整个切换器 UI;传了即接管,仍受 mode: 'toggle' 自 gate
light{ theme, resolved }浅色态图标(覆盖默认 sun,仅默认 UI 生效)
dark{ theme, resolved }深色态图标(覆盖默认 moon,仅默认 UI 生效)
auto{ theme, resolved }跟随系统态图标(覆盖默认半圆,仅 3 态 + 默认 UI)

皮肤 Token

Token作用
--sw-theme-switch-size按钮宽高
--sw-theme-switch-color / --sw-theme-switch-hover-color图标色 / hover 图标色
--sw-theme-switch-bg / --sw-theme-switch-hover-bg背景 / hover 背景
--sw-theme-switch-radius圆角

注意事项

  • 自 gate 决定显隐:theme.mode 非 toggle 时组件渲染空——想让用户能切主题,在 swift.config.json 设 theme.mode: 'toggle'(详见 主题系统)。
  • size 仅作用于默认内联图标:换图标 slot 或默认作用域插槽自渲染时,尺寸由你自己的内容决定。
  • 无对外事件:切换由内部 toggleTheme 驱动;要监听主题变化直接 watch useTheme() 的 theme / resolvedTheme。

相关