> 文章列表 > 前端实战(三):element-ui的二次封装

前端实战(三):element-ui的二次封装

前端实战(三):element-ui的二次封装

目录

二次封装 Switch 开关

原始效果

设计效果

实现步骤


在日常开发过程中,大多数项目主要以 vue 为主,并且现在很多公司仍在使用着 vue。但在使用element-ui组件时通常会遇到一些问题:如组件样式与设计不符合、组件不存在某个功能等等;故本文主要探讨使用了element-ui的项目可以怎么封装一些比较通用化的组件。

二次封装 Switch 开关

表示两种相互对立的状态间的切换,多用于触发「开/关」

原始效果:

 

设计效果:

实现步骤:

  • 新建公共子组件MomSwitch.vue
<template><el-switch class="switchStyle" v-model="value" :active-value="activeValue" :inactive-value="inactiveValue":width="width" :active-text="activeText" :inactive-text="inactiveText" :active-color="activeColor":inactive-color="inactiveColor" :disabled="disabled" :value="value"></el-switch>
</template><script>
export default {model: {prop: "value",event: "change",},props: {width: {type: Number,default: ''},activeText: {type: String,default: ''},inactiveText: {type: String,default: ''},activeValue: {type: Number,default: 1},inactiveValue: {type: Number,default: 0},activeColor: {type: String,default: ''},inactiveColor: {type: String,default: ''},disabled: {type: Boolean,default: false},value: {type: Number,default: 0},},watch: {value(val) {this.$emit("change", val);},},
}
</script><style>
.switchStyle .el-switch__label {position: absolute;display: none;color: #080d15;
}.switchStyle .el-switch__label--left {z-index: 9;left: 20px;
}.switchStyle .el-switch__label--right {z-index: 9;left: -4px;
}.switchStyle .el-switch__label.is-active {display: block;
}
</style>

关键代码:

        在封装一个组件时,在使用v-model的时候,需要定制prop和event。因为默认情况下,一个组件上的v-model会把value用作prop、把input用作event,但是在我自定义的组件里,需求的与默认情况不符。因此需要配置子组件接收的 prop 名称,以及派发的事件名称(即定制prop和event)来使用v-model。

        代码块中关于样式的写法以及原因请点击下方链接查看详情:

         关于element-ui的样式覆盖问题_覆盖element样式_@李优秀的博客-CSDN博客关于element-ui组件样式深度覆盖不生效的解决办法以及注意事项https://blog.csdn.net/weixin_48168510/article/details/127446746?spm=1001.2014.3001.5502

  • 父组件中引用公共子组件
<template><el-container style="height:100%" ref="bodyform"><MomSwitch v-model="customFormData.ishassn" width="41" activeText="有" inactiveText="无"></MomSwitch></el-container>
</template><script>
import MomSwitch from '@/CommonComponents/MomSwitch.vue';
export default {components: {MomSwitch},data:function () {return {customFormData:{ishassn:0}}        }
}
</script><style></style>

到这里就大功告成啦,后续还会不断更新!也欢迎大家指出我的问题!