css变量方式换肤方案

271 阅读1分钟

前言

现在越来越多的网站都提供了拥有换肤(切换主题)功能,如 ElementUI,既是为了迎合用户需求,或是为了凸显自己特点,因此提供了个性化定制的功能.

换肤方案分三种这里直接介绍终极解决方案

  1. 方案一 添加类名法
  2. 方案二 多套样式法
  3. 方案三 css变量法(本文重点讲述)

css变量法流程

graph LR
start -->  获取颜色变量 --> Js操作设置根元素变量 --> 修改css内部变量

第一步. 服务端获取皮肤配置对象

// 该配置服务端获取
{
  '--themeEle1color':'#333',
  '--themeEle1bgcolor':'#eee'
  ...
}

第二步. vue根元素应用

<!--// themeParams 服务端返回皮肤对象 -->
<template>
  <div class="root" :style="themeParams">
</template>

第四步. css文件应用该变量

body{
    color:var(--themeEle1color);
    background:var(themeEle1bgcolor)
}

完整demo代码


<template>
	<view class="container" :style="themeParams">
		<button @click="changeTheme(0)" :class="{'active':index===0}">theme1</button>
		<button @click="changeTheme(1)" :class="{'active':index===1}">theme2</button>
		<button @click="changeTheme(2)" :class="{'active':index===2}">theme3</button>
		<view class="block ele1">
			ele1
		</view>
		<view class="block ele2">
			ele2
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				themeParams:{},
				themes:[
					{
						'--ele1-color':"#ff00ff",
						'--ele1-bg-color':'#dfd',
						'--ele2-color':"#444",
						'--ele2-bg-color':'#aaa',
					},
					{
						'--ele1-color':"#000",
						'--ele1-bg-color':'#fff',
						'--ele2-color':"#555",
						'--ele2-bg-color':'#ddd',
					},
					{
						'--ele1-color':"#00ff00",
						'--ele1-bg-color':'#f00',
						'--ele2-color':"#009900",
						'--ele2-bg-color':'#990000',
					}
					
				],
				index:0
			}
		},
		mounted(){
			this.themeParams = this.themes[this.index]
			setTimeout(()=>{
				this.index = 2
				this.themeParams = this.themes[2]
				
			},10000)
			
		},
		
		methods: {
			changeTheme(index){
				this.$nextTick(()=>{
					this.index = index
					this.themeParams=this.themes[index]
					
				})
				
			}

		}
	}
</script>

<style>
	.block {
		width: 100%;
		height: 250px;
		border: 1px solid #eee;
	}
	.active{
		background: #ff0000;
		color: #fff;
	}
	.block.ele1{
		color: var(--ele1-color);
		background-color: var(--ele1-bg-color);
	}
	.block.ele2{
		color: var(--ele2-color);
		background-color: var(--ele2-bg-color);
	}
	
	
</style>