有如下代码要实现换肤功能
{{ msg }}
Red
Green
Blue
name:'app',
data() {return{
msg:'Dynamic Themes',
theme:'red'}
},
computed: {
themeClass() {return `theme-${this.theme}`;
}
}
}
这里通过一个下拉框应用不用主题
首先我们把主题变量抽取出来
$themes: (
red: (
font-color: red,
),
green: (
font-color: green
),
blue: (
font-color: blue
),
);
这里包含三个主题red,gredd,blue,每个主题内的font-color变量对应不同的值,
然后我们写一个主题化的mixin,包括一个themed函数
@mixin themify($themes: $themes) {
@each $theme-name, $map in $themes {
.theme-#{$theme-name} & {
$theme-map: () !global;
@each $key, $value in $map {
$theme-map: map-merge($theme-map, ($key: $value)) !global;
}
@content;
$theme-map: null !global;
}
}
}
@function themed($key) {
@return map-get($theme-map, $key);
}
这段代码的功能主要是对需要主体化的地方,对样式根据不同主题的变量进行替换,然后复制一份样式代码
使用方式如下
.app-container {
@include themify($themes) {
color: themed('font-color');
}
}
至此,主题换肤功能完成