如何一次处理多个SASS映射?

问题描述 投票:0回答:1

我正在尝试动态创建实用程序类。

在SASS内可以定义地图,然后在@each处使用以基于地图的keyvalue生成类。但是,需要在property中手动添加css @each。我想要一个可以添加该元素和一些基于地图数据的命名约定的函数。因此,基于以下示例,我想动态添加flex-direction,而不必为每个地图创建@each

什么有效

//Example Map
@flex-wrap: ("nw": "no-wrap", "w": "wrap", "wr": "wrap-reverse")

//Example @each
@each $name, $value in $flex-wrap
    .flx-w-#{$name}
        flex-direction: #{$value}

我需要什么

.flx + $prefix + $name
    $property: $value

和预期的已编译CSS结果

.flx-d-w {
    flex-direction: wrap;
}
css function sass flexbox maps
1个回答
0
投票

一种执行所需操作的动态方法是使用嵌套映射,两个@each循环和一个mixin。

$flex-direction: (
  "name": "flex-direction",
  "prefix": "flx-d",
  "values": (
    "r": "row",
    "c": "column",
    "rr": "row-reverse",
    "cr": "column-reverse"
  )
);

$flex-wrap: (
  "name": "flex-wrap",
  "prefix": "flx-w",
  "values": (
    "nw": "nowrap",
    "w": "wrap",
    "wr": "wrap-reverse"
  )
);

@mixin createClasses($maps...) {
  @each $map in $maps {
    $propertyName: map-get($map, "name");
    $propertyPrefix: map-get($map, "prefix");

    @each $value, $key in map-get($map, "values") {
      .#{$propertyPrefix}-#{$value} {
        #{$propertyName}: #{$key};
      }
    }
  }
}

@include createClasses($flex-direction, $flex-wrap);

使用上面的示例,您将获得:

.flx-d-r {
  flex-direction: row;
}

.flx-d-c {
  flex-direction: column;
}

.flx-d-rr {
  flex-direction: row-reverse;
}

.flx-d-rc {
  flex-direction: column-reverse;
}

.flx-w-nw {
  flex-wrap: nowrap;
}

.flx-w-w {
  flex-wrap: wrap;
}

.flx-w-wr {
  flex-wrap: wrap-reverse;
}

这里的“魔术”部分正在使用散布...运算符来传递您想要在mixin(documentation here)中使用的任意数量的地图。您只需在所有地图上调用一次即可,它将创建您所有的类。


SASS版本的代码:

$flex-direction: ("name": "flex-direction", "prefix": "flx-d", "values": ("r": "row", "c": "column", "rr": "row-reverse", "cr": "column-reverse"))
$flex-wrap: ("name": "flex-wrap", "prefix": "flx-w", "values": ("nw": "nowrap", "w": "wrap", "wr": "wrap-reverse"))

=createClasses($maps...)
  @each $map in $maps
    $propertyName: map-get($map, "name")
    $propertyPrefix: map-get($map, "prefix")
    @each $value, $key in map-get($map, "values")
      .#{$propertyPrefix}-#{$value}
        #{$propertyName}: #{$key}

+createClasses($flex-direction, $flex-wrap)
© www.soinside.com 2019 - 2024. All rights reserved.