菜鸟读element源码三 el-col

2,173 阅读2分钟

内容

以下是我模仿并注释的代码

模仿代码中均以el-test 替换el, 目的是为了边模仿边测试和el组件的效果对比

export default {
  name: 'ElTestCol',

  // col组件所接受参数
  props: {
    // 宽度 默认为24
    span: {
      type: Number,
      default: 24
    },
    // 偏移量
    offset: Number,
    // 左侧偏移量
    pull: Number,
    // 右侧偏移量
    push: Number
  },

  computed: {
    gutter () {
      let parent = this.$parent
      //循环找到row组件或者row不存在跳出循环。
      while (parent && parent.$options.componentName !== 'ElTestRow') {
        parent = this.$parent
      }
      return parent ? parent.gutter : 0
    }
  },

  render(h) {
    let classStyle = []
    let style = {}

    if (this.gutter) {
      style.paddingLeft = `${this.gutter/2}px`
      style.paddingRight = style.paddingLeft
    }

    // 遍历属性 查询对应的class
    ['span', 'offset', 'pull', 'push'].forEach(prop => {
      //保证属性存在时才添加class
      if(this[prop] || this[prop]===0)
        classStyle.push(
          prop !== 'span'?
          `el-test-col-${prop}-${this[prop]}`:
          `el-test-col-${this[prop]}`
        )
    })
    return h('div', 
    {
      class: ['el-test-col', classStyle],
      style
    }, 
    this.$slots.default)
  },
}

看了col的源码 ,加上自己的实践, 感觉el-col和el-row是应该嵌套起来使用(觉得可以减少计算gutter时候的循环消耗)。

另外就是在实现col.css的时候,发现其实有很多class长的十分相似,源码中是这样

    .el-col-1 {
  width: 4.16667%;
}
.el-col-offset-1 {
  margin-left: 4.16667%;
}
.el-col-pull-1 {
  right: 4.16667%;
}
.el-col-push-1 {
  left: 4.16667%;
}
.el-col-2 {
  width: 8.33333%;
}
.el-col-offset-2 {
  margin-left: 8.33333%;
}
.el-col-pull-2 {
  right: 8.33333%;
}
.el-col-push-2 {
  left: 8.33333%;
}
.el-col-3 {
  width: 12.5%;
}

如果能够进行循环就好了,这时候阅读了索尼大佬的文章,发现了scss的强大作用 如果我们把上述css用scss实现

@for $i from 0 through 24 {
  // 栅格宽度
  .el-test-col-#{$i}{
    width: (1 / 24 * 100 * $i) * 1%;
    border: 1px solid #DCDCDC;
  }

  // 栅格右移
  .el-test-col-offset-#{$i}{
    margin-left: (1 / 24 * 100 * $i) * 1%;
  }

  // 栅格左移
  .el-test-col-pull-#{$i}{
    right:  (1 / 24 * 100 * $i) * 1%;
  }

  // 栅格右移
  .el-test-col-push-#{$i}{
    left:  ( 1 / 24 * 100 * $i) * 1%;
  }
}

是不是很简洁,如果用css 需要24个col 24个push 24个pull 24个offset 并且维护也会很麻烦。

疑问一 css是scss打包生成的吗?打包scss生成css要怎么做

element的文件夹下不仅有css文件 还有对应的scss文件,有没有大佬知道css是scss文件打包后生成的吗?因为我觉得 好像没有必要说 scss写一遍,css再来一遍

总结

col组件相对简单,没什么值得特别注意的,当然可以顺手学一波scss还是很有必要的。 顺便说一下 scss文件放在 element-ui/packages/theme-chalk/src