vue实现黑夜主题
使用 CSS 变量实现主题切换
在 Vue 项目中,可以通过 CSS 变量动态切换主题。定义两套颜色变量,分别对应白天和黑夜主题。
/* 全局样式文件 */
:root {
--bg-color: #ffffff;
--text-color: #333333;
--primary-color: #409eff;
}
[data-theme="dark"] {
--bg-color: #1a1a1a;
--text-color: #f0f0f0;
--primary-color: #5a9cf8;
}
在组件中使用这些变量:
.container {
background-color: var(--bg-color);
color: var(--text-color);
}
在 Vue 中管理主题状态
使用 Vue 的响应式特性来管理当前主题状态。可以创建一个全局状态或使用 Vuex/Pinia。
// 使用 reactive
import { reactive } from 'vue';
const themeStore = reactive({
isDark: false,
toggleTheme() {
this.isDark = !this.isDark;
document.documentElement.setAttribute('data-theme', this.isDark ? 'dark' : 'light');
}
});
持久化主题选择
将用户选择的主题保存到 localStorage,确保刷新后保持主题一致。
// 初始化时读取本地存储
const savedTheme = localStorage.getItem('theme');
if (savedTheme) {
themeStore.isDark = savedTheme === 'dark';
document.documentElement.setAttribute('data-theme', savedTheme);
}
// 切换主题时保存
function toggleTheme() {
themeStore.toggleTheme();
localStorage.setItem('theme', themeStore.isDark ? 'dark' : 'light');
}
使用第三方库简化实现
可以考虑使用现成的主题切换库,如 vue-use 的 useDark 组合式函数:
import { useDark, useToggle } from '@vueuse/core';
const isDark = useDark();
const toggleDark = useToggle(isDark);
过渡动画增强体验
为主题切换添加平滑的过渡效果,提升用户体验。
* {
transition: background-color 0.3s ease, color 0.3s ease;
}





