技术栈:vue2.X + element-ui
该组件可实现对按钮样式,事件,权限等等的配置控制。
前言
封装组件是项目中重要的一项。如何的封装一个共用、易用的组件呢?
开始
场景:如下图:实现一个可配置的功能按钮栏。
考虑到vue是数据驱动视图。所以我们尽量把配置判断封装到组件中,然后通过数据去判断不同的功能类型。
使用
<template>
<yus-tool-bar :tools="tools"></yus-tool-bar>
</template>
<script>
export default {
data () {
return {
tools: [
{
label: '刷新', // 文字
type: 'text', // 类型 可参考element-ui文档
auth: 'addTable', // 权限
show: true, // 传boolean 类型或者 下面function
// show: () => return true,
icon: 'iconfont icon-shuaxin1', // 按钮
disabled: true, // 禁用 传boolean类型或者 下面function
// disabled: () => return false,
// 点击回调调用
func: () => {
this.notify()
}
},
{
label: '新增',
auth: 'addTable', // 权限
icon: 'iconfont icon-xinzeng',
type: 'warning',
func: () => {
this.notify('新增的方法')
}
},
{
label: '删除',
auth: 'deleteTable',
icon: 'iconfont icon-shanchu',
func: () => {
this.notify('删除的方法')
}
}
]
}
}
}
</script>
组件代码
话不多说,直接贴代码:
<template>
<div class="yus-tool-bar">
<div class="tool-list">
<template v-for="(tool, idx) in tools">
<el-button v-show="setShow(tool)"
:key="idx"
:size="tool.size || 'mini'"
:icon="tool.icon || ''"
v-auth="tool.auth || null"
:type="tool.type || 'primary'"
:plain="tool.plain || false"
:round="tool.round || false"
:circle="tool.circle || false"
:disabled="setDisabled(tool)"
@click.stop="handleClick(tool)">{{tool.label}}</el-button>
</template>
</div>
</div>
</template>
<script>
export default {
name: 'yus-tool-bar',
props: {
tools: {
type: Array,
default: () => []
}
},
methods: {
handleClick (tool) {
if (!tool.func) {
return
}
tool.func()
},
setDisabled (tool) {
if (tool.disabled && typeof tool.disabled === 'function') {
return tool.disabled()
}
return tool.disabled
},
setShow (tool) {
if (tool.show && typeof tool.show === 'function') {
return tool.show()
}
return !!tool.show || true
}
}
}
</script>
<style scoped lang="scss">
.yus-tool-bar {
.tool-list {
text-align: left;
font-size: 14px;
/deep/ .iconfont {
margin-right: 5px;
font-size: 12px;
}
}
}
</style>
总结
以上可根据自己公司的业务需求做更改后食用。通过封装的方式高度实现组件的共用性,样式和代码的统一性。