vue 中使用sass实现主体换肤

有如下代码要实现换肤功能

<template>
<div class="app-root" :class="themeClass">
<div class="app-container">
<p>{{ msg }}</p>
<select v-model="theme">
<option value="red">Red</option>
<option value="green">Green</option>
<option value="blue">Blue</option>
</select>
</div>
</div>
</template>
<script>
export default {
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);
}

  这段代码的功能主要是对需要主体化的地方,对样式根据不同主题的变量进行替换,然后复制一份样式代码

使用方式如下

<style lang="scss" scoped>
@import './styles/theming';
.app-container {
@include themify($themes) {
color: themed('font-color');
}
}
</style>

至此,主题换肤功能完成

上一篇:C# web api返回类型设置为json的两种方法


下一篇:在Java中为什么不同的返回类型不算方法重载?