Sass变量默认作用域

15

我在使用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; 

}

它被编译为:

.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保留其已定义的值。

我做错了什么?

1个回答

21

在class1中局部定义$val: 'green'并不会改变mixin中的默认值$val: 'red' !default,因为它寻找全局的$val。此时,还没有定义全局的$val。

然后全局$val被定义为'black'。这之后,在mixin中的$val将寻找全局的$val。此时,全局$val已经被定义为'black'。

再次在本地定义$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'

2
SASS团队从JS中借用这种作用域的决定非常令人恼火和奇怪,我个人认为。 - Alexander Presber

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接