Sass variable default scope

江枫思渺然 提交于 2019-12-29 04:16:12

问题


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?


回答1:


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'


来源:https://stackoverflow.com/questions/5469931/sass-variable-default-scope

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!