1. 準備兩個less文件:
1.1 theme.less 用於定義控制樣式的函數
.theme(
@Background: #1D2B40,
@Border: #000017,
){
.header{
background: @Background;
border-bottom: 1px solid @Border;
}
}
2.2 color.less 用於調用函數傳值
@import url('./theme.less');
/* 黑色主題(默認主題) */
.theme_default {
.theme()
}
/* 藍色主題(傳入要更換的顏色) */
.theme_blue{
.theme(
@Background: #377DFF,
@Border: #0167DF,
)
}
2. 在main.js導入color.less 作爲全局樣式:
import './less/color.less';
3.添加點擊換膚的事件:
<DropdownMenu slot="list" >
<DropdownItem @click.native="changeTheme('theme_default')">黑色風格</DropdownItem>
<DropdownItem @click.native="changeTheme('theme_blue')">藍色風格</DropdownItem>
</DropdownMenu>
//點擊換膚事件
changeTheme(theme){
//給body添加class名,並將該class保存到localstorage中
document.body.className = theme;
localStorage.setItem('themeColor', theme);
//把當前主題值傳到其他組件...
//areaUtil.$emit('changeThemes', theme);
}
4. 在index.html文件裏給body初始化的時候添加class:
<script>
var bodyClass = localStorage.getItem('themeColor') ? localStorage.getItem('themeColor') : 'theme_default';
document.body.className = bodyClass;
</script>
優點:易於理解,快速上手
缺點:需要把組件中需要換顏色或圖標的樣式單獨拎出來寫,不方便維護,因此應該注意變量名語義化、多寫註釋