聊一聊BEM設計模式在Vue組件開發中的應用

聊一聊BEM設計模式在Vue組件開發中的應用

回想一下在你的前端生涯中是否遇到過如下問題
1.在寫css的時候常常會在命名class時絞盡腦汁
2.在團隊多人開發中出現css命名衝突
3.在進行組件化開發時如何規範書寫csscss

什麼是BEM

BEM是Yandex團隊提出的一種css的命名方式,經過這種命名方式能夠很好地解決上面遇到的問題,提升css的開發效率和可讀性html

進入BEM的世界

  • B: 表示塊,能夠抽象成一個組件前端

  • E: 表示元素,組件下的一個元素,多個元素造成一個組件設計模式

  • M:表示修飾符,能夠用來表示元素的狀態,好比激活狀態,顏色,大小ecmascript

BEM這貨究竟張啥樣呢,顏值高不高,請看下面的代碼組件化

.block {}
    .block__element {}
    .block__element--modifier {}

看完後你的心裏會不會在想,臥槽,這貨竟然這麼醜,名字還這麼長,醜拒...spa

__和--鏈接符這是什麼鬼

  • __主要用來表示塊(B)和元素(E)間的鏈接設計

  • --用來表示塊或者元素與狀態的鏈接code

好比咱們要作寫一個button的組件,能夠這麼來component

/* 有一個叫button的組件 */
    .button {
         dispaly: inline-block;
         pading: 10px;
     } 

    /* btn組件下面有一個顯示圖標的元素 */
    .button__icont {
          font-size: 12px;
     }
    
    /* btn組件有好多顏色能夠選擇  */
    .button--primary {
        background: blue;
    }

    .button--success {
        background: green;
     }

    .button--warning {
        background: red;
     }
<div class="button button--primary">
        <span class="button__text">藍色按鈕</span>
    </div>

   <div class="button button--success">
        <span class="button__text">綠色按鈕</span>
    </div>

   <div class="button button--warning">
        <span class="button__text">紅色按鈕</span>
    </div>

在Vue中結合Stylus預編譯器使用BEM規範

<template>
  <div class="button" :class="[type ? 'button--primary' : '']">
    <i class="button__icon"></i>
    <span class="button__text"> {{ text }} </span>
  </div>
</template>

<style lang="stylus" rel="stylesheet/stylus" scoped>
  .button
    background: #dedede
    &__icon
      font-size: 12px
    &__text
      color: #fff
    &--primary
      background: blue;
    &--success
      background: green
</style>

<script type="text/ecmascript-6">
  export default {
    props: {
      type: {
            type: String
      },
      text: {
            type: String
       }
    },
    data () {
      return {}
    },
    components: {}
  }
</script>
相關文章
相關標籤/搜索