vue暗黑模式实现
暗黑模式基础实现
在Vue项目中实现暗黑模式通常涉及CSS变量、状态管理和动态样式切换。以下是常见方法:
定义CSS变量 在全局CSS或根组件中定义两套颜色变量:
:root {
--bg-color: #ffffff;
--text-color: #333333;
--primary-color: #409eff;
}
[data-theme="dark"] {
--bg-color: #1a1a1a;
--text-color: #f0f0f0;
--primary-color: #5a9cf8;
}
使用Vue状态管理 通过Vuex或Pinia存储当前主题状态:
// store/modules/theme.js
export default {
state: () => ({
darkMode: false
}),
mutations: {
toggleDarkMode(state) {
state.darkMode = !state.darkMode
}
}
}
动态切换主题
组件内切换逻辑 在组件中添加切换按钮和方法:
<template>
<button @click="toggleTheme">切换主题</button>
</template>
<script>
export default {
methods: {
toggleTheme() {
this.$store.commit('toggleDarkMode')
document.documentElement.setAttribute(
'data-theme',
this.$store.state.theme.darkMode ? 'dark' : 'light'
)
}
}
}
</script>
持久化存储 使用localStorage保存用户选择:
// App.vue
export default {
mounted() {
const savedTheme = localStorage.getItem('theme')
if (savedTheme) {
this.$store.commit('setDarkMode', savedTheme === 'dark')
document.documentElement.setAttribute('data-theme', savedTheme)
}
}
}
进阶实现方案
CSS预处理器支持 在Sass/Less中使用变量:
$themes: (
light: (
bgColor: white,
textColor: black
),
dark: (
bgColor: #1a1a1a,
textColor: white
)
);
@mixin theme($property, $key) {
@each $theme-name, $theme-colors in $themes {
.theme-#{$theme-name} & {
#{$property}: map-get($theme-colors, $key)
}
}
}
Element UI集成 针对Element UI组件库的暗黑模式:
import Element from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
import './assets/dark-theme.css' // 自定义暗色样式
// 根据状态切换主题
function setElementTheme(isDark) {
if (isDark) {
document.body.classList.add('dark-theme')
} else {
document.body.classList.remove('dark-theme')
}
}
系统偏好检测
自动匹配系统主题 通过媒体查询检测系统偏好:
// 检测系统颜色方案
const prefersDark = window.matchMedia('(prefers-color-scheme: dark)')
// 初始设置
if (prefersDark.matches) {
store.commit('setDarkMode', true)
}
// 监听系统主题变化
prefersDark.addListener((e) => {
store.commit('setDarkMode', e.matches)
})
过渡动画优化 添加平滑的主题切换过渡效果:
* {
transition: background-color 0.3s ease, color 0.2s ease;
}






