有一需求: 全站UI切换主题色, 支持夜间模式, 用户可以自定义主题色, 颜色控制精度要高要灵活. 围绕这一需求尝试了多种方案, 放弃了多种方案, 直到最后一种方案被确定.
建立了多个分支, 敲了好多代码, 都没合并到master中, 但在尝试中对vue的学习更深入了.
sass利用它的语法自动生成大量class模板:
$base-color: #ff9090;
.pink {
@each $attr in background-color, color, border-color, caret-color {
.#{$attr} {
#{$attr}: $base-color;
}
@for $i from 1 through 20 {
.#{$attr}-darken-#{$i} {
#{$attr}: darken($base-color, $i);
}
.#{$attr}-lighten-#{$i} {
#{$attr}: lighten($base-color, $i);
}
@each $pseudo in hover, focus {
.#{$pseudo}-#{$attr}-darken-#{$i} {
&:#{$pseudo} {
#{$attr}: darken($base-color, $i);
}
}
.#{$pseudo}-#{$attr}-lighten-#{$i} {
&:#{$pseudo} {
#{$attr}: lighten($base-color, $i);
}
}
}
}
}
}
结论:上面多个循环函数编译的css模板, 利用class嵌套可以自由切换全站UI, 但还是不够灵活, 用户不能自定义,sass是预编译css资源文件, 不能和js进行联动, 学习了sass语法和在vue中的应用
利用vue的模板语法结合vuex能很好的注入动态style
全局vuex
state: {
mode: 'light', // another is dark
currentTheme: 'pink',
theme,
},
getters快速设置style object
import color from '@/utils/color';
export default {
color: state => state.theme[state.currentTheme],
style: state => ({
property,
}) => ({
[property]: state.theme[state.currentTheme],
}),
styleLighten: state => ({
property,
light = 0,
}) => ({
[property]: color(state.theme[state.currentTheme]).lighten(light),
}),
styleDarken: state => ({
property,
dark = 0,
}) => ({
[property]: color(state.theme[state.currentTheme]).darken(dark),
}),
styleMode: state => ({
property,
value,
}) => ({
[property]: state.mode === 'light' ? value : color(value).negate(),
}),
};
注入动态的style, 数组型style更方便
:style="[
styleMode({property: 'background-color', value:'#fff'}),
styleMode({property: 'color', value:'#333'}),
]"
结论:但是有个问题,pseudo class实现起来很麻烦, :hover, :focus...,但这次尝试学习了很多vue基本知识点
搜索了下资料,无意看到vue作者的一段话
If you prefer fully dynamic styling, you can always use a CSS-in-JS option with Vue instead.
最后决定使用CSS-in-JS, 只是需要引入一个库,styled-components的概念.
找了下, 找到一个vue-styled-components, 这个库对于我来说太熟悉了, 它其实是React的一个很火的库, 叫styled-components, 组织名和库名都叫这, 所以react才是它的主打, vue-styled-components是组织下的一个为vue打造的库, 关注量不多(400+),和react的styled-components关注量(21,000+)也不能比, 先了解下,关键在于它是否是当前项目的良好解决方案.
到底有没有使用vue-styled-components, 下一篇将介绍最终的方案
多次尝试后的收获.