1.css樣式的一種解耦的寫法
- 以type爲例,type有多種值,最中這值會反應到css上。在整個實現思路中沒有出現if else 的判斷
<el-button type="primary">主要按鈕</el-button>
<el-button type="success">成功按鈕</el-button>
<el-button type="info">信息按鈕</el-button>
<el-button type="warning">警告按鈕</el-button>
<el-button type="danger">危險按鈕</el-button>
el-button中props定義的變量
props: {
// 主題類型 primary / success / warning / danger / info / text
type: {
type: String,
default: 'default'
},
}
- class的綁定操作,type的值由調用組件的使用者決定,這裏將得到‘‘el-button–’ + type ’(比如:el-button–primary)
<button
class="el-button"
:class="[
type ? 'el-button--' + type : '',
]"
>
- 相應的css類,將被自動匹配上
.el-button--primary {
color: #fff;
background-color: #409eff;
border-color: #409eff;
}
.el-button--warning {
color: #fff;
background-color: #e6a23c;
border-color: #e6a23c;
}
2.css的屬性值寫法
- 以round爲例
<el-button type="primary" round>主要按鈕</el-button>
el-button中props定義的變量,
props: {
// 上面的寫法 只有'round'屬性名,這裏必須爲Boolean,這樣round的值爲true。
// 如果是其他類型,round會爲空
round: Boolean,
}
- class的動態綁定操作,可以同時用兩種寫法。1.數組綁定,2.數組的項爲一個對象(見vue文檔)
<button
class="el-button"
:class="[
type ? 'el-button--' + type : '',
buttonSize ? 'el-button--' + buttonSize : '',
{
'is-round': round,
'is-circle': circle
}
]"
>
- 相應的css類
.el-button.is-round {
border-radius: 20px;
padding: 12px 23px;
}
3.動態判斷插槽的值,去掉不必要的節點
具名插槽也可以做這種判斷,當父組件中沒有給值,就可以去掉
//$slots.default 包含了所有沒有具字插槽的節點。
<span v-if="$slots.default"><slot></slot></span>