vue实现主题选色
Vue 实现主题选色方案
方案一:CSS 变量 + Vue 动态绑定
在 :root 或组件中定义 CSS 变量,通过 Vue 动态修改这些变量实现主题切换。
/* 全局样式文件 */
:root {
--primary-color: #42b983;
--secondary-color: #35495e;
}
<template>
<div :style="{'--primary-color': currentColor}">
<button @click="changeTheme('#ff0000')">红色主题</button>
</div>
</template>
<script>
export default {
data() {
return {
currentColor: '#42b983'
}
},
methods: {
changeTheme(color) {
this.currentColor = color
document.documentElement.style.setProperty('--primary-color', color)
}
}
}
</script>
方案二:Vuex 状态管理 + 类名切换
使用 Vuex 存储当前主题信息,通过动态类名应用不同样式。
// store.js
export default new Vuex.Store({
state: {
theme: 'light'
},
mutations: {
setTheme(state, theme) {
state.theme = theme
}
}
})
<template>
<div :class="`theme-${$store.state.theme}`">
<button @click="$store.commit('setTheme', 'dark')">深色主题</button>
</div>
</template>
<style>
.theme-light {
--primary-color: #ffffff;
}
.theme-dark {
--primary-color: #000000;
}
</style>
方案三:Element UI 主题定制
对于使用 Element UI 的项目,可以通过官方主题工具实现。
-
安装主题生成工具:
npm install element-theme -g -
初始化变量文件:
et -i -
修改生成的
element-variables.scss文件中的颜色变量 -
编译主题:
et -
在项目中引入编译后的主题文件
方案四:SCSS 变量 + Webpack 动态加载
利用 Webpack 的 style-loader 实现动态主题加载。
// theme/default.scss
$primary-color: blue;
// theme/red.scss
$primary-color: red;
// webpack配置
{
test: /\.scss$/,
use: [
{
loader: 'style-loader',
options: {
insert: function insertAtTop(element) {
const parent = document.querySelector('head')
parent.insertBefore(element, parent.firstChild)
}
}
},
'css-loader',
'sass-loader'
]
}
<script>
export default {
methods: {
loadTheme(themeName) {
import(`@/styles/themes/${themeName}.scss`)
}
}
}
</script>
方案五:Tailwind CSS 动态主题
使用 Tailwind 的 JIT 模式结合 Vue 实现动态主题。
// tailwind.config.js
module.exports = {
mode: 'jit',
theme: {
extend: {
colors: {
primary: {
DEFAULT: 'var(--primary-color)',
}
}
}
}
}
<template>
<div class="text-primary">
<input type="color" v-model="userColor" @change="updateColor">
</div>
</template>
<script>
export default {
data() {
return {
userColor: '#3b82f6'
}
},
methods: {
updateColor() {
document.documentElement.style.setProperty('--primary-color', this.userColor)
}
}
}
</script>
每种方案适用于不同场景,CSS 变量方案最轻量,Vuex 方案适合复杂应用,UI 框架方案适合对应生态项目。根据项目需求选择最合适的实现方式。







