Element-Ui源码学习【1】 - Layout、Container、Icon、Button、Link

Layout

Row

export default {
    // 文件名
    name: 'ElRow',

    // 组件名,注册时使用
    componentName: 'ElRow',

    props: {
        // 创建 el-row 标签时,在DOM中显示的标签,默认为 div
        tag: {
            type: String,
            default: 'div'
        },
        // 间隔像素
        gutter: Number,
        // row使用的display类型,默认是 block,可以设置为 flex
        type: String,
        // 当 type == flex 时,水平方向上的分布
        justify: {
            type: String,
            default: 'start'
        },
        // 当 type == flex 时,垂直方向上的分布
        align: String
    },

    computed: {
        // 设置间隔,通过设置当前 row 层 margin 左右值为“负值”确保内容不会超出
        style() {
            const ret = {};

            if (this.gutter) {
                ret.marginLeft = `-${this.gutter / 2}px`;
                ret.marginRight = ret.marginLeft;
            }

            return ret;
        }
    },

    render(h) {
        // JSX 实现 DOM 部分,使用参数控制 class 类名,style 控制样式,增加插槽放置内容
        return h(this.tag, {
            class: [
                'el-row',
                this.justify !== 'start' ? `is-justify-${this.justify}` : '',
                this.align ? `is-align-${this.align}` : '',
                { 'el-row--flex': this.type === 'flex' }
            ],
            style: this.style
        }, this.$slots.default);
    }
};

Col

export default {
  name: 'ElCol',

  props: {
    // 栅格占据的列数,全列共分为24子列
    span: {
      type: Number,
      default: 24
    },
    // 自定义元素标签
    tag: {
      type: String,
      default: 'div'
    },
    // 左侧间隔栅格
    offset: Number,
    // 栅格向右移动
    pull: Number,
    // 栅格向左移动
    push: Number,
    xs: [Number, Object],
    sm: [Number, Object],
    md: [Number, Object],
    lg: [Number, Object],
    xl: [Number, Object]
  },

  computed: {
    gutter() {
      let parent = this.$parent;
      // 循环向上查找 ElRow 确定间隔
      // TODO 这里可能存在双层父级是ElRow的问题 
      while (parent && parent.$options.componentName !== 'ElRow') {
        parent = parent.$parent;
      }
      return parent ? parent.gutter : 0;
    }
  },
  render(h) {
    let classList = [];
    let style = {};

    // 根据 ElRow 设置的间隔确定 ElCol 的左右padding
    if (this.gutter) {
      style.paddingLeft = this.gutter / 2 + 'px';
      style.paddingRight = style.paddingLeft;
    }

    // 通过 props 中的传参直接确定 ElCol 上的 class类
    ['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]}`
        );
      }
    });

    ['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]}`
          );
        });
      }
    });

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

总结

  1. 布局类使用类似于 jsx 的写法,可以动态渲染外层标签。
  2. props 中的部分参数可以仅指定类型,而不指定 default 或者 validator,虽然校验上稍弱,但是可拓展性强。
  3. 子元素可以通过 while 循环 this.$parent 查找匹配的父级。

Container

Container

<template>
  <section class="el-container" :class="{ 'is-vertical': isVertical }">
    <slot></slot>
  </section>
</template>
  
<script>
export default {
  name: 'ElContainer',

  componentName: 'ElContainer',

  props: {
    // 子元素的排列方向
    direction: String
  },

  computed: {
    // 判断当前元素的排列方向
    isVertical() {
      if (this.direction === 'vertical') {
        return true;
      } else if (this.direction === 'horizontal') {
        return false;
      }
      // 如果不指定方向,则根据插槽中的元素进行判断
      return this.$slots && this.$slots.default
        ? this.$slots.default.some(vnode => {
          // 根据虚拟DOM中的tag判断当前组件的名字
          const tag = vnode.componentOptions && vnode.componentOptions.tag;
          return tag === 'el-header' || tag === 'el-footer';
        })
        : false;
    }
  }
};
</script>

Header

<template>
  <header class="el-header" :style="{ height }">
    <slot></slot>
  </header>
</template>
  
<script>
export default {
  name: 'ElHeader',

  componentName: 'ElHeader',

  props: {
    height: {
      type: String,
      default: '60px'
    }
  }
};
</script>

Aside

<template>
  <aside class="el-aside" :style="{ width }">
    <slot></slot>
  </aside>
</template>
  
<script>
export default {
  name: 'ElAside',

  componentName: 'ElAside',

  props: {
    width: {
      type: String,
      default: '300px'
    }
  }
};
</script>

Main

<template>
    <main class="el-main">
        <slot></slot>
    </main>
</template>
  
<script>
export default {
    name: 'ElMain',
    componentName: 'ElMain'
};
</script>

Footer

<template>
    <footer class="el-footer" :style="{ height }">
        <slot></slot>
    </footer>
</template>
  
<script>
export default {
    name: 'ElFooter',

    componentName: 'ElFooter',

    props: {
        height: {
            type: String,
            default: '60px'
        }
    }
};
</script>

总结

  1. 通过对 this.$slot.default 中的子组件进行循环,判断 componentOptions.tag 的名字是不是子组件的名字。
  2. flex布局通过 flex: 1 保证内容填充满。

Icon

<template>
    <i :class="'el-icon-' + name"></i>
</template>
  
<script>
export default {
    name: 'ElIcon',

    props: {
        //TODO 这里的图标是怎么被引入进来的,未找到
        name: String
    }
};
</script>

Button

<template>
  <button class="el-button" @click="handleClick" :disabled="buttonDisabled || loading" :autofocus="autofocus"
    :type="nativeType" :class="[
      type ? 'el-button--' + type : '',
      buttonSize ? 'el-button--' + buttonSize : '',
      {
        'is-disabled': buttonDisabled,
        'is-loading': loading,
        'is-plain': plain,
        'is-round': round,
        'is-circle': circle
      }
    ]">
    <!-- loading和图标互斥,且loading中为disabled状态 -->
    <i class="el-icon-loading" v-if="loading"></i>
    <i :class="icon" v-if="icon && !loading"></i>
    <!-- 判断只有插槽存在内容的状态下才存在span -->
    <span v-if="$slots.default">
      <slot></slot>
    </span>
  </button>
</template>
<script>
export default {
  name: 'ElButton',

  inject: {
    elForm: {
      default: ''
    },
    elFormItem: {
      default: ''
    }
  },

  props: {
    // 按钮类型,可选【	primary / success / warning / danger / info / text】
    // 仅添加 default,而不通过 validator 进行定向匹配,留下拓展性(也有可能是懒)
    type: {
      type: String,
      default: 'default'
    },
    // 按钮大小,可选【medium / small / mini】
    size: String,
    // 按钮内图标,直接是图标类名,匹配图标class
    icon: {
      type: String,
      default: ''
    },
    // 原生type属性,默认是button,可选【button / submit / reset】
    // 这里可以不用validator进行校验,因为w3c默认只有三种type,其他的不生效
    // 在w3c中推荐显式指定 type=button,在ie中默认 type=button ,其他浏览器默认 type=submit
    nativeType: {
      type: String,
      default: 'button'
    },
    // 是否loading
    loading: Boolean,
    // 是否禁用
    disabled: Boolean,
    // 是否是朴素按钮样式
    plain: Boolean,
    // 是否默认聚焦(用处不大,除非是确认类型的弹窗)
    autofocus: Boolean,
    // 是否圆角按钮
    round: Boolean,
    // 是否圆形按钮
    circle: Boolean
  },

  computed: {
    _elFormItemSize() {
      return (this.elFormItem || {}).elFormItemSize;
    },
    // 按钮大小根据 props 判断,根据 form 中的size 判断,根据全局判断(方便进行全局性调整)
    buttonSize() {
      return this.size || this._elFormItemSize || (this.$ELEMENT || {}).size;
    },
    // 确定按钮的 disabled 状态
    // 判断 props 中是否存在 disbaled,因为 disabled 可能为 false,所以这里使用的 hasOwnProperty 方法
    // 首选根据 props 确定,其次根据 form 确定
    // eslint 限制 this.$options.propsData.hasOwnProperty('disabled') 这种写法,可以换成 Object.prototype.hasOwnProperty.call()
    buttonDisabled() {
      return Object.prototype.hasOwnProperty.call(this.$options.propsData, 'disabled') ? this.disabled : (this.elForm || {}).disabled;
    }
  },

  methods: {
    // 点击事件直接回调
    handleClick(evt) {
      this.$emit('click', evt);
    }
  }
};
</script>

总结

  1. 判断 props 中的部分参数是否存在,可以使用 Object.prototype.hasOwnProperty 方法进行确定。
  2. 按钮 loading 状态同 disabled 状态。

Link

<template>
    <a :class="[
        'el-link',
        type ? `el-link--${type}` : '',
        disabled && 'is-disabled',
        underline && !disabled && 'is-underline'
    ]" :href="disabled ? null : href" v-bind="$attrs" @click="handleClick">

        <i :class="icon" v-if="icon"></i>

        <span v-if="$slots.default" class="el-link--inner">
            <slot></slot>
        </span>

        <template v-if="$slots.icon">
            <slot v-if="$slots.icon" name="icon"></slot>
        </template>
    </a>
</template>
  
<script>

export default {
    name: 'ElLink',

    props: {
        // 类型,可选【primary / success / warning / danger / info】,默认 default。
        // 主要是颜色区分
        type: {
            type: String,
            default: 'default'
        },
        // 是否下划线
        underline: {
            type: Boolean,
            default: true
        },
        // 是否禁用
        // 主要是从颜色、href、回调事件上禁用
        disabled: Boolean,
        // 原生href属性
        href: String,
        // 图标
        // 图标主要是直接指定 icon class 类名,也可以通过插槽 slot='icon' 进行展示
        icon: String
    },

    methods: {
        // click 点击回调
        handleClick(event) {
            if (!this.disabled) {
                if (!this.href) {
                    this.$emit('click', event);
                }
            }
        }
    }
};
</script>

总结

  1. link 的 disabled 状态需要从三个方面限制:样式、href、click回调。
  • 10
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值