Sass 变量默认作用域 [英] Sass variable default scope
问题描述
我在跨范围使用 Sass 中的变量默认值时遇到问题.我的测试示例是:
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;
}
编译为:
.bar {
color: "red";
}
.class1 .bar {
color: "red";
}
.class1 .class11 .bar {
color: "red";
}
.class2 .bar {
color: "black";
}
.class3 .bar {
color: "blue";
}
.class4 .bar {
color: "blue";
}
如你所见,变量 $val 在 mixin foo 中被定义为 'red' !default.我希望导入 mixin 会将 $val 设置为 'red' ,除非它已经定义.但是,在 class1 中,$val 在本地定义为green",导入 mixin foo 会用red"覆盖它.在其他类中,在 $val 全局定义为 'black' 之后,导入 mixin 会按预期工作,并且 $val 保留其已定义的值.
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.
我做错了什么?
推荐答案
在 class1 本地定义 $val: 'green'
不会改变 $val: 'red' !default
code> 在 mixin 中,因为它寻找全局 $val.此时,还没有定义全局 $val.
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.
然后全局 $val 被定义为 'black'.在 mixin 中的 $val 之后查找全局 $val.至此,全局$val已经被定义为'black'.
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'.
在本地再次定义 $val 将改变已定义的全局 $val.
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'
这篇关于Sass 变量默认作用域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!