在学习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>
复制代码
完整代码请访问:组件代码学习