vue实现平台换新
Vue实现平台换肤方案
动态CSS变量方案
通过CSS变量结合Vue的响应式特性实现换肤
在:root或组件中定义CSS变量
:root {
--primary-color: #409EFF;
--bg-color: #f5f7fa;
}
在Vue组件中动态修改变量值
document.documentElement.style.setProperty('--primary-color', newColor)
主题文件切换方案
准备多套主题CSS文件
const themes = {
light: {
primary: '#409EFF',
background: '#f5f7fa'
},
dark: {
primary: '#304156',
background: '#1c1f23'
}
}
使用Vuex或Pinia管理当前主题
// store/modules/theme.js
export default {
state: () => ({
currentTheme: 'light'
}),
mutations: {
setTheme(state, themeName) {
state.currentTheme = themeName
}
}
}
组件库主题定制
对于Element UI等组件库 使用官方主题工具生成多套CSS
et -c ./src/assets/theme/light.json -o ./src/assets/theme/light.css
et -c ./src/assets/theme/dark.json -o ./src/assets/theme/dark.css
动态加载主题文件
function loadTheme(themeName) {
const link = document.getElementById('theme-link')
link.href = `/static/theme/${themeName}.css`
}
持久化存储
使用localStorage保存用户选择
// 保存主题
localStorage.setItem('theme', 'dark')
// 初始化时读取
const savedTheme = localStorage.getItem('theme') || 'light'
store.commit('setTheme', savedTheme)
完整实现示例
创建ThemeProvider组件
<template>
<div :class="`theme-${currentTheme}`">
<slot />
</div>
</template>
<script>
import { computed } from 'vue'
import { useStore } from 'vuex'
export default {
setup() {
const store = useStore()
const currentTheme = computed(() => store.state.theme.currentTheme)
return { currentTheme }
}
}
</script>
主题切换方法
function toggleTheme() {
const newTheme = currentTheme.value === 'light' ? 'dark' : 'light'
store.commit('setTheme', newTheme)
localStorage.setItem('theme', newTheme)
loadThemeCss(newTheme)
}
性能优化建议
使用CSS变量而非多套样式文件减少请求 对大型应用采用按需加载主题策略 添加过渡效果提升用户体验
.theme-transition * {
transition: background-color 0.3s, color 0.3s;
}





