参考这篇SO帖子和文档 。
如果您只是简单地定义一个变量两次,则第二个定义会按预期延迟加载,但如果您通过mixin执行此操作,则它似乎是相反的,因此应用第一个解锁。
.mixin(@input) { @width: @input; } .selector { width: @var; } @var: 30px; @var: 40px; .mixin(20px); .mixin(30px); .selector-2 { width: @width; }输出:
.selector { width: 40px; } .selector-2 { width: 20px; }有人可以解释一下吗?
In reference to this SO post and the docs.
If you simply define a variable twice, the 2nd definition gets lazy loaded as expected but if you do this through a mixin, it seems to be reversed, so the first unlock is applied.
.mixin(@input) { @width: @input; } .selector { width: @var; } @var: 30px; @var: 40px; .mixin(20px); .mixin(30px); .selector-2 { width: @width; }Output:
.selector { width: 40px; } .selector-2 { width: 20px; }Can someone explain this?
最满意答案
仅当范围尚未定义此类变量时,mixin中的变量才会暴露到其调用范围中。 (文档中没有专门的部分,但这里提到了 )。
在您的示例中.mixin(30px)没有效果,因为@width已经通过之前的.mixin调用(即.mixin(20px) )解锁到作用域中。
这里有关于这种行为的讨论,但似乎没有办法在不破坏许多重要的Less设计模式的情况下改变它。
-
顺便说一句,另一个相关的例子:
.mixin() { @width: 10px; } .mixin() { @width: 20px; } .selector { .mixin(); width: @width; }在这种情况下,结果是20px因为两个mixin同时扩展,最后一个@width定义获胜。
Variable in a mixin is exposed into its calling scope only if the scope does not already have such variable defined. (There's no dedicated section in the docs, but it's mentioned here).
In your example .mixin(30px) has no effect because @width is already unlocked into the scope by the previous .mixin call (i.e. .mixin(20px)).
There's discussion regarding this behaviour here, but it seems there's no way to change it without breaking many important Less design patterns.
-
Btw., another related example:
.mixin() { @width: 10px; } .mixin() { @width: 20px; } .selector { .mixin(); width: @width; }In this case the result is 20px because both mixins are expanded simultaneously and the last @width definition wins.
更多推荐
发布评论