Vue组件开发

5次阅读

共计 1601 个字符,预计需要花费 5 分钟才能阅读完成。

在学习 vue 的时候,发现有很多使用 vue 开发的 ui 组件。本着学习的目的,自己也仿照 Element 写一些组件。
使用 VuePress 编写组件文档。
单元测试:karma+mocha+chai+sinon。
文档预览地址:预览链接
使用 VuePress 编辑文档的代码访问:组件文档关于 VuePress 使用方法:博客园、掘金
完整代码:组件代码
接下来就是编写组件,首先以常用的组件 Button 为例。
通过 props 属性接收父组件传递过来的值,并对传递过来的值进行类型验证。
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>

完整代码请访问: 组件代码

正文完
 0