在學習vue
的時候,發現有不少使用vue
開發的ui組件。本着學習的目的,本身也仿照Element寫一些組件。html
使用VuePress編寫組件文檔。vue
單元測試:karma
+mocha
+chai
+sinon
。git
文檔預覽地址:預覽連接github
使用VuePress
編輯文檔的代碼訪問:組件文檔 關於VuePress
使用方法:博客園、掘金bash
完整代碼:組件代碼app
接下來就是編寫組件,首先以經常使用的組件Button
爲例。ide
經過props屬性
接收父組件傳遞過來的值,並對傳遞過來的值進行類型驗證。post
props:{
type:{
type: String,
validator (value) {
return [
'primary',
'success',
'info',
'warning',
'danger'
].indexOf(value)>-1;
}
},
iconName:{
type:String
},
iconSize:{
type:String,
default:'small'
},
iconPosition:{
type: String,
default: 'left',
validator(value){
return[
'left',
'right'
].indexOf(value)>-1
}
},
circle:{
type: Boolean
},
disabled:{
type: Boolean
}
}
複製代碼
經過 props
接收父組件傳遞的值,能夠實現各類功能不同的button
組件。單元測試
<template>
<button @click="handleClick" class="vi-button" :disabled="disabled" :class=buttonClass>
<span class="vi-button-wrapper" :class=wrapperClass>
<span v-if="iconName" class="vi-button-icon">
<vi-icon :viIconName="iconName" :viIconSize="iconSize"></vi-icon>
</span>
<span class="vi-button-content">
<slot></slot>
</span>
</span>
</button>
</template>
<script>
export default {
name: 'ViButton',
props:{
type:{
type: String,
validator (value) {
return [
'primary',
'success',
'info',
'warning',
'danger'
].indexOf(value)>-1;
}
},
iconName:{
type:String
},
iconSize:{
type:String,
default:'small'
},
iconPosition:{
type: String,
default: 'left',
validator(value){
return[
'left',
'right'
].indexOf(value)>-1
}
},
circle:{
type: Boolean
},
disabled:{
type: Boolean
}
},
methods: {
handleClick(event) {
this.$emit('click', event);
}
},
computed:{
buttonClass(){
return {
[`vi-button-${this.type}`]:this.type,
[`vi-button-disabled`]:this.disabled,
[`vi-button-circle`]:this.circle
}
},
wrapperClass(){
return {
[`vi-button-${this.iconPosition}`]:this.iconName&&this.iconPosition
}
}
}
}
</script>
複製代碼
完整代碼請訪問:組件代碼學習