Sass variable default scope
I have a problem with using variable defaults in Sass across scopes. My test example is:
@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;
}
It is compiles to:
.bar {
color: "red";
}
.class1 .bar {
color: "red";
}
.class1 .class11 .bar {
color: "red";
}
.class2 .bar {
color: "black";
}
.class3 .bar {
color: "blue";
}
.class4 .bar {
color: "blue";
}
As you can see, variable $val is defined as 'red' !default in the mixin foo. I expect that 开发者_运维知识库importing the mixin would set $val to 'red' unless it is already defined. However, in class1, where $val is locally defined as 'green', importing the mixin foo overwrites it with 'red'. In other classes, after the global definition of $val as 'black', importing the mixin works as expected and $val retains its already defined value.
What am I doing wrong?
Defining $val: 'green'
locally in class1 does not alter $val: 'red' !default
in mixin, because it look for global $val. At this point, no global $val has been defined.
Then global $val is defined as 'black'. After this $val in mixin look for global $val. At this point, global $val has been defined as 'black'.
Defining $val again locally will alter global $val that has been defined.
@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'
精彩评论