前言
早就听说过使用BEM命名管理样式,平时在项目中也有用到,但总感觉写起来太麻烦,最近刚好在看Elementplus源码,发现Elementplus使用BEM的方案非常棒,本文就来结合ElementPlus源码分析一下如何在项目中优雅的使用BEM命名
BEM的介绍
BEM是一种针对css的前端命名规范,**是块(Block),元素(Element),修饰符(Modifier)**的简写。
Block可以理解为模块,比如:article,dialog,sidebar,form,tab
Element可以理解为块里的元素,比如form里面的input,submit
modifier可以理解为对block或者element的修饰,比如修饰form__submit–disable,form–theme-dark
BEM的命名规范
.block { }
.block__element { }
.block--modifier { }
.block__element--modifier { }
使用__来连接block和element,使用–来连接block和modifier
清楚了概念和命名规范,下面我们就来看ElementPlus是怎么实现BEM的
BEM的实践
<template>
<div class="dialog-overlay" v-if="visible">
<section class="dialog">
<header class="dialog__header">
<div class="dialog-title">{
{ title }}</div>
<span class="dialog-header__close" @click="visible=false">X</span>
</header>
<div class="dialog__body">
{
{ message }}
</div>
<footer class="dialog__footer">
<button class="dialog__btn">{
{ cancelBtnTxt }}</button>
<button class="dialog__btn dialog__btn--primary">{
{ comfirmBtnTxt }}</button>
</footer>
</section>
</div>
</template>
<script setup lang="ts"> import { ref } from 'vue'
const props = defineProps({
title:{
type:String,
default:'Title'
},
message:String,
cancelBtnTxt:{
type:String,
default:'Cancel'
},
comfirmBtnTxt:{
type:String,
default:'Comfirm'
}
})
const visible = ref(true)
const close = ()=>{
visible.value = false
} </script>
<style scoped lang="scss"> :global(body){
font-family: PingFang SC,Microsoft YaHei,Arial,sans-serif;
}
.dialog-overlay{
position: fixed;
top: 0;
right: 0;
bottom: 0;
left: 0;
z-index: 2000;
height: 100%;
background-color:rgba(0, 0, 0, .5);
overflow: auto;
}
.dialog {
position: fixed;
left: 50%;
top: 50%;
transform: translate(-50%,-50%);
border-radius:2px;
background: #fff;
width: 559px;
min-height: 200px;
&__header{
padding: 20px 20px 10px;
}
&__title{
color: #333;
font-size: 18px;
}
&__body{
padding: 30px 20px;
font-size: 14px;
color: #333;
}
&-close{
position: absolute;
right: 15px;
top: 15px;
color: #999;
font-size: 18px;
}
&__btn{
min-width: 33px;
padding: 8px 1