1. <el-row :gutter="20">
  2. <el-col :span="6" :offset="6"><div class="grid-content bg-purple"></div></el-col>
  3. <el-col :span="6" :offset="6"><div class="grid-content bg-purple"></div></el-col>
  4. </el-row>

组件模板

  1. <div class="el-row">
  2. <slot></slot>
  3. </div>
  4. render(h) {
  5. return h(this.tag, {
  6. class: [
  7. 'el-row',
  8. ]
  9. }, this.$slots.default);
  10. }
  1. <div class="el-col">
  2. <slot></slot>
  3. </div>
  4. render(h) {
  5. return h(this.tag, {
  6. class: [
  7. 'el-col',
  8. ]
  9. }, this.$slots.default);
  10. }

el-col

  1. computed: {
  2. gutter() {
  3. let parent = this.$parent;
  4. while (parent && parent.$options.componentName !== 'ElRow') {
  5. parent = parent.$parent;
  6. }
  7. return parent ? parent.gutter : 0;
  8. }
  9. },
  10. render(h) {
  11. let classList = [];
  12. classList.push(`el-col-${this.span}`);
  13. let style = {};
  14. if (this.gutter) {
  15. style.paddingLeft = this.gutter / 2 + 'px';
  16. style.paddingRight = style.paddingLeft;
  17. }
  18. return h(this.tag, {
  19. class: [
  20. 'el-col',
  21. classList
  22. ]
  23. }, this.$slots.default);
  24. }

使用 provide/inject 的方式去把祖先节点的实例注入到子组件中

  1. // el-row 组件中
  2. provide() {
  3. return {
  4. row: this
  5. };
  6. }
  7. // el-col 组件
  8. inject: ['row']

el-row

  1. computed: {
  2. style() {
  3. const ret = {};
  4. if (this.gutter) {
  5. ret.marginLeft = `-${this.gutter / 2}px`;
  6. ret.marginRight = ret.marginLeft;
  7. }
  8. return ret;
  9. }
  10. },
  11. render(h) {
  12. return h(this.tag, {
  13. class: [
  14. 'el-row',
  15. ],
  16. style: this.style
  17. }, this.$slots.default);
  18. }

参考资料

  1. Element源码分析系列1一Layout(布局)
  2. Element-UI 技术揭秘(3)— Layout 布局组件的设计与实现