vue实现主题选色
Vue 实现主题选色方案
使用 CSS 变量动态切换
定义全局 CSS 变量,通过修改变量值实现主题切换:
/* 全局样式文件 */
:root {
--primary-color: #409EFF;
--secondary-color: #67C23A;
}
.dark-theme {
--primary-color: #304156;
--secondary-color: #4e6e8e;
}
在 Vue 组件中动态切换类名:
// 切换主题方法
methods: {
toggleTheme() {
document.documentElement.classList.toggle('dark-theme')
}
}
基于 Vuex 的状态管理方案
创建 Vuex store 管理主题状态:
// store.js
export default new Vuex.Store({
state: {
theme: 'light'
},
mutations: {
setTheme(state, theme) {
state.theme = theme
}
}
})
在组件中动态应用主题:
<template>
<div :class="currentTheme">
<!-- 内容 -->
</div>
</template>
<script>
export default {
computed: {
currentTheme() {
return this.$store.state.theme
}
}
}
</script>
使用第三方库方案
安装 vue-theme-switcher 等专用库:
npm install vue-theme-switcher
实现示例:
import ThemeSwitcher from 'vue-theme-switcher'
Vue.use(ThemeSwitcher, {
themes: {
light: {
primary: '#409EFF'
},
dark: {
primary: '#304156'
}
}
})
持久化存储方案
结合 localStorage 保存用户选择:
methods: {
setTheme(theme) {
this.$store.commit('setTheme', theme)
localStorage.setItem('user-theme', theme)
},
loadTheme() {
const savedTheme = localStorage.getItem('user-theme')
if (savedTheme) {
this.$store.commit('setTheme', savedTheme)
}
}
},
created() {
this.loadTheme()
}
动态样式计算方案
使用计算属性动态生成样式:
<template>
<div :style="themeStyle">
<!-- 内容 -->
</div>
</template>
<script>
export default {
computed: {
themeStyle() {
return {
'--primary-color': this.$store.state.theme === 'dark' ? '#304156' : '#409EFF'
}
}
}
}
</script>






