Mil*_*šić 15 variables scope sass mixins defaults
我在跨范围的Sass中使用变量默认值时遇到问题.我的测试例子是:
@mixin foo {
$val: 'red' !default;
.bar {
color: $val;
}
}
@include foo;
.class1 {
$val: 'green';
@include foo;
.class11 {
@include foo;
}
}
$val: 'black';
.class2 {
@include foo;
}
.class3 {
$val: 'blue';
@include foo;
}
.class4 {
@include foo;
}
Run Code Online (Sandbox Code Playgroud)
它编译为:
.bar {
color: "red";
}
.class1 .bar {
color: "red";
}
.class1 .class11 .bar {
color: "red";
}
.class2 .bar {
color: "black";
}
.class3 .bar {
color: "blue";
}
.class4 .bar {
color: "blue";
}
Run Code Online (Sandbox Code Playgroud)
如您所见,变量$ val在mixin foo中被定义为'red'!default.我希望导入mixin会将$ val设置为'red',除非它已经定义.但是,在class1中,$ val在本地定义为'green',导入mixin foo会用'red'覆盖它.在其他类中,在$ val的全局定义为"black"之后,导入mixin按预期工作,$ val保留其已定义的值.
我究竟做错了什么?
ray*_*ibi 21
$val: 'green'
在class1中本地定义不会$val: 'red' !default
在mixin中改变,因为它寻找全局$ val.此时,尚未定义全局$ val.
然后全局$ val定义为"黑色".在mixin中这个$ val之后寻找全球$ val.此时,全局$ val已定义为"黑色".
在本地再次定义$ val将改变已定义的全局$ val.
@mixin foo
$val: 'red' !default // defined locally
.bar
color: $val
@include foo // $val in mixin foo look for global $val. no global $val found, then 'red'
.class1
$val: 'green'
@include foo // $val in mixin foo look for global $val. no global $val found, then 'red'
color: $val // local $val 'green'
.class11
@include foo // $val in mixin foo look for global $val. no global $val found, then 'red'
$val: 'black' // defined globally at the first time
.class2
@include foo // $val in mixin foo look for global $val. $val found, 'black'
.class3
$val: 'blue' // change the gobal $val
@include foo // $val in mixin foo look for global $val. $val found, 'blue'
.class4
@include foo // $val in mixin foo look for global $val. $val found, 'blue'
Run Code Online (Sandbox Code Playgroud)