vue+iview+less 实现一键换肤
传送门:Less 快速入门
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>
优点:易于理解,快速上手开发
缺点:需要把组件中需要换颜色或图标的样式单独拎出来写,不方便维护,因此应该注意变量名语义化、多写注释
还没有评论,来说两句吧...