Vue如何实现主题暗黑
Vue 实现暗黑主题的方法
使用 CSS 变量和动态类名
在 Vue 项目中,可以通过 CSS 变量和动态类名切换主题。定义两套 CSS 变量,分别对应亮色和暗黑主题,通过切换类名实现主题变化。
:root {
--bg-color: #ffffff;
--text-color: #333333;
}
.dark-theme {
--bg-color: #1a1a1a;
--text-color: #f0f0f0;
}
body {
background-color: var(--bg-color);
color: var(--text-color);
}
在 Vue 组件中,使用 v-bind:class 动态切换类名:
<template>
<div :class="{ 'dark-theme': isDark }">
<!-- 内容 -->
</div>
</template>
<script>
export default {
data() {
return {
isDark: false
}
},
methods: {
toggleTheme() {
this.isDark = !this.isDark
}
}
}
</script>
使用 Vuex 或 Pinia 管理主题状态
对于大型项目,可以使用状态管理工具(如 Vuex 或 Pinia)集中管理主题状态,方便全局切换。
// store.js (Vuex)
export default new Vuex.Store({
state: {
isDark: false
},
mutations: {
toggleTheme(state) {
state.isDark = !state.isDark
}
}
})
在组件中通过 mapState 和 mapMutations 使用:
<template>
<div :class="{ 'dark-theme': isDark }">
<button @click="toggleTheme">切换主题</button>
</div>
</template>
<script>
import { mapState, mapMutations } from 'vuex'
export default {
computed: {
...mapState(['isDark'])
},
methods: {
...mapMutations(['toggleTheme'])
}
}
</script>
结合 localStorage 持久化主题
为了避免用户每次刷新页面都需要重新切换主题,可以将主题状态保存到 localStorage 中。
// 在 Vuex 或组件中
methods: {
toggleTheme() {
this.isDark = !this.isDark
localStorage.setItem('theme', this.isDark ? 'dark' : 'light')
}
},
created() {
const savedTheme = localStorage.getItem('theme')
if (savedTheme) {
this.isDark = savedTheme === 'dark'
}
}
使用第三方库
对于更复杂的主题需求,可以考虑使用第三方库如 vue-use 或 vuetify,它们提供了内置的主题切换功能。
// 使用 vue-use
import { useDark, useToggle } from '@vueuse/core'
const isDark = useDark()
const toggleDark = useToggle(isDark)
响应系统主题变化
通过 window.matchMedia 监听系统主题变化,自动切换暗黑模式。
mounted() {
const darkModeMediaQuery = window.matchMedia('(prefers-color-scheme: dark)')
this.isDark = darkModeMediaQuery.matches
darkModeMediaQuery.addEventListener('change', (e) => {
this.isDark = e.matches
})
}
以上方法可以根据项目需求灵活组合使用,实现完整的暗黑主题功能。







