el-row el-col 源码解析

371 阅读1分钟

el-row el-col源码解析

el-row

以下是el-row 的源代码,使用render函数渲染,可以修改渲染的tag,默认为div。 可以设置type属性为flex,使容器使用flex布局。 使用justify align属性来分别修改主轴在垂直方向、水平方向的布局。

PixPin_2024-02-13_13-17-55.png

el-col

以下是el-col的源代码,也是采用render函数渲染,可以修改tag,渲染不同的元素。

return h(this.tag, {
    class: ['el-col', classList],
    style
  }, this.$slots.default);
}

下面是el-col中classList的代码,可以看到对应el-col中的四个属性

span offset pull push

['span', 'offset', 'pull', 'push'].forEach(prop => {
      if (this[prop] || this[prop] === 0) {
        classList.push(
          prop !== 'span'
            ? `el-col-${prop}-${this[prop]}`
            : `el-col-${this[prop]}`
        );
      }
    });
@for $i from 0 through 24 {
  // 栅格宽度
  .el-col-#{$i} {
    width: (1 / 24 * $i * 100) * 1%;
  }

  // 栅格左侧间距
  .el-col-offset-#{$i} {
    margin-left: (1 / 24 * $i * 100) * 1%;
  }

  // 栅格右移距离
  .el-col-pull-#{$i} {
    position: relative;
    right: (1 / 24 * $i * 100) * 1%;
  }

  // 栅格左移距离
  .el-col-push-#{$i} {
    position: relative;
    left: (1 / 24 * $i * 100) * 1%;
  }
}

下面对应的是栅格响应式的代码, 也是在el-col中添加对应的class

 ['xs', 'sm', 'md', 'lg', 'xl'].forEach(size => {
      if (typeof this[size] === 'number') {
        classList.push(`el-col-${size}-${this[size]}`);
      } else if (typeof this[size] === 'object') {
        let props = this[size];
        Object.keys(props).forEach(prop => {
          classList.push(
            prop !== 'span'
              ? `el-col-${size}-${prop}-${props[prop]}`
              : `el-col-${size}-${props[prop]}`
          );
        });
      }
    });

对于不同的响应式属性,是通过媒体查询实现的

@include res(xs) {
  .el-col-xs-0 {
    display: none;
  }
  @for $i from 0 through 24 {
    .el-col-xs-#{$i} {
      width: (1 / 24 * $i * 100) * 1%;
    }

    .el-col-xs-offset-#{$i} {
      margin-left: (1 / 24 * $i * 100) * 1%;
    }

    .el-col-xs-pull-#{$i} {
      position: relative;
      right: (1 / 24 * $i * 100) * 1%;
    }

    .el-col-xs-push-#{$i} {
      position: relative;
      left: (1 / 24 * $i * 100) * 1%;
    }
  }
}
@mixin res($key, $map: $--breakpoints) {
  // 循环断点Map,如果存在则返回
  @if map-has-key($map, $key) {
    @media only screen and #{inspect(map-get($map, $key))} {
      @content;
    }
  } @else {
    @warn "Undefeined points: `#{$map}`";
  }
}