打造本身的UI庫--分割線篇

上篇講解了按鈕組件的開發過程。vue

接下來的主角是另外一個很常見的組件:分割線git

使用場景

顧名思義,爲了達到更好的閱讀效果,合理地對內容進行分割,這就是分割線。咱們來看下今天要開發的幾種分割線的實際效果:github

大致就是:bash

  • 普通分割線
  • 垂直分割線
  • 文字分割線
  • 虛線分割線
  • 以及以上分割線的組合使用

定義props

看看咱們定義了哪些props來完成以上的幾個功能:markdown

props: {
    // 水平或者垂直
    type: {
      type: String,
      default: "horizontal"
    },
    // 文字對齊(居左、居中、居右)
    orientation: {
      type: String,
      default: "center"
    },
    // 虛線
    dashed: {
      type: Boolean,
      default: false
    },
    // 大小
    size: {
      type: String,
      default: "default"
    }
  }
複製代碼

Template

Template描述的是組件的外形結構,本組件能夠分爲三層,分別是:最外層的div、中間層的span、以及文字的slotless

<template>
  <div :class="classes">
    <span v-if="hasSlot" :class="slotClasses">
      <slot />
    </span>
  </div>
</template>
複製代碼

CSS類的計算

經過整合傳入的props,爲Template應用上相關的class,因此這部分都在computed中實現:ide

computed: {
    // 判斷是否傳入文字
    hasSlot() {
      return !!this.$slots.default;
    },
    // 外層div的class
    classes() {
      return [
        `${prefixCls}`,
        `${prefixCls}-${this.type}`,
        ...
      ];
    },
    // 中間層span的class
    slotClasses() {
      return [`${prefixCls}-inner-text`];
    }
}
複製代碼

重頭戲:CSS

首先看下水平或者垂直是怎麼控制的:

.@{divider-prefix-cls} {
    background: @border-color-split;
    &-vertical{
        display: inline-block;
        margin: 0 8px;
        height: 0.9em;
        width: 1px;
        vertical-align: middle;
        position: relative;
        top: -0.06em;
    }
    &-horizontal {
        display: block;
        height: 1px;
        width: 100%;
        min-width: 100%;
        margin: 24px 0;
        clear: both;
    }
}
複製代碼

帶有文字

.@{divider-prefix-cls} {
    background: @border-color-split;
    ...
    &-horizontal&-with-text-center,
    &-horizontal&-with-text-left,
    &-horizontal&-with-text-right {
        display: table;
        white-space: nowrap;
        text-align: center;
        background: transparent;
        margin: 16px 0;
        font-size: 16px;
        &:before,
        &:after{
            content: '';
            display: table-cell;
            position: relative;
            top: 50%;
            width: 50%;
            border-top: 1px solid @border-color-split;
            transform: translateY(50%);
        }
    }
    ...
複製代碼

控制文本對齊

// ...
    &-horizontal&-with-text-left {
        &:before {
            top: 50%;
            width: 5%;
        }
        &:after {
            top: 50%;
            width: 95%;
        }
    }

    &-horizontal&-with-text-right {
        &:before {
            top: 50%;
            width: 95%;
        }
        &:after {
            top: 50%;
            width: 5%;
        }
    }
    // ...
複製代碼

CSS這塊的代碼不是很好講解,雖然用到的都是平時常見的屬性,可是能提煉到如此簡潔的地步,並非那麼容易,建議你們完整地看下CSS部分的代碼divider.lessoop

更多源碼

以整個的代碼結構和思想來自ViewUI,真心以爲ViewUI的代碼比ElementUI的容易閱讀和學習(我的觀點)post

項目源碼學習

divider.vue

divider.less

相關文章
相關標籤/搜索