ThemeSwitch 主题切换
主题切换组件,用于切换系统的明暗主题模式。
🎯 在线体验:登录 https://vue.youlai.tech 后,点击右上角导航栏的主题切换图标即可体验。
功能特性
- 🌓 主题切换 - 支持明亮/暗黑主题切换
- 🎨 图标显示 - 根据当前主题显示对应图标
- 💾 状态持久化 - 主题设置自动保存
- 🌍 国际化 - 支持多语言显示
基础用法
vue
<template>
<ThemeSwitch />
</template>
<script setup lang="ts">
import ThemeSwitch from '@/components/ThemeSwitch/index.vue'
</script>在导航栏中使用
vue
<template>
<div class="navbar">
<div class="navbar-right">
<ThemeSwitch />
<LangSelect />
<UserDropdown />
</div>
</div>
</template>主题模式
| 模式 | 图标 | 说明 |
|---|---|---|
| light | ☀️ Sunny | 明亮主题 |
| dark | 🌙 Moon | 暗黑主题 |
与 Store 集成
组件使用 useSettingsStore 管理主题状态:
typescript
import { useSettingsStore } from '@/store'
import { ThemeMode } from '@/enums'
const settingsStore = useSettingsStore()
// 获取当前主题
const currentTheme = settingsStore.theme
// 设置主题
settingsStore.theme = ThemeMode.DARK主题枚举
typescript
enum ThemeMode {
LIGHT = 'light',
DARK = 'dark'
}样式定制
scss
// 自定义切换按钮样式
:deep(.el-dropdown) {
.el-icon {
font-size: 20px;
cursor: pointer;
&:hover {
color: var(--el-color-primary);
}
}
}
// 下拉菜单样式
:deep(.el-dropdown-menu__item) {
display: flex;
align-items: center;
gap: 8px;
.el-icon {
font-size: 16px;
}
}国际化配置
组件使用以下国际化 key:
json
{
"login": {
"light": "浅色模式",
"dark": "深色模式"
}
}注意事项
- CSS 变量:主题切换依赖 CSS 变量实现
- Element Plus:自动同步 Element Plus 的主题模式
- 持久化:主题设置会保存到本地存储
