有如下代碼要實現換膚功能
<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>
至此,主題換膚功能完成
