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。

相關