您的位置:首页 > 娱乐 > 八卦 > vue2组件封装实战系列之tag组件

vue2组件封装实战系列之tag组件

2024/10/6 20:38:05 来源:https://blog.csdn.net/qq_27702739/article/details/139527591  浏览:    关键词:vue2组件封装实战系列之tag组件

作为本系列的第一篇文章,不会过于的繁杂,并且前期的组件都会是比较简单的基础组件!但是不要忽视这些基础组件,因为纵观elementui、elementplus还是其他的流行组件库,组件库的封装都是套娃式的,很多复杂组件会用到基础组件,所以我们要打好基础,做好基础组件的封装,才能为后期的难度大的组件做好准备。

组件之GfTag

tag组件,类似于按钮组件,功能比按钮的少,可以说是精简版的按钮

效果预览

在这里插入图片描述

属性

参数类型说明可选值默认值
textString标签的内容--
closableBoolean是否可关闭true/falsefalse
hitBoolean是否有边框描边true/falsefalse
disableTransitionsBoolean是否禁用渐变动画true/falsefalse
colorString背景色any
sizeString标签的内容medium / small / mini
effectString标签的内容dark / light / plainlight

代码实现

这里我们使用了function组件来实现tag组件,比较简洁灵活

<script>
export default {//组件的名字,我们在注册的时候使用name: "GfTag",props: {text: String,closable: Boolean,type: String,hit: Boolean,disableTransitions: {type: Boolean,default: true,},color: String,size: String,effect: {type: String,default: "light",validator(val) {return ["dark", "light", "plain"].indexOf(val) !== -1;},},},computed: {tagSize() {//this.$ELEMENT是挂在在Vue.prototype.$ELEMENT上的属性return this.size || (this.$ELEMENT || {}).size;},},methods: {//点击标签抛出的回调事件handleClick(e) {this.$emit("click", e);},//关闭标签抛出的回调事件handleClose(e) {e.stopPropagation();this.$emit("close", e);},},render(h) {const { type, tagSize, hit, effect } = this;const classes = ["el-tag",type ? `el-tag--${type}` : "",tagSize ? `el-tag--${tagSize}` : "",hit && "is-hit",effect && `el-tag--${effect}`,];const tagEle = (<spanclass={classes}style={{ backgroundColor: this.color }}onClick={this.handleClick}>{this.$slots.default ? this.$slots.default : this.text}{this.closable && (<i class="el-tag__close el-icon-close" onClick={this.handleClose}></i>)}</span>);return this.disableTransitions ? (tagEle) : (<transitions name="el-zoom-in-center">{tagEle}</transitions>);},
};
</script>

样式文件可以参考elementui的实现,后面会写一篇文章详细分析组件库的样式怎么去写的文章,敬请关注

使用

    <Gf-space flex gap="10"><gf-tagclosable@close="handleTagClose"v-for="item in tags":key="item.name":type="item.type">{{ item.name }}</gf-tag></Gf-space><Gf-space flex gap="10" direction="column"><gf-tagclosableeffect="dark"@close="handleTagClose"v-for="item in tags":key="item.name":type="item.type">{{ item.name }}</gf-tag></Gf-space>

在这里插入图片描述
这样,我们就实现了自己的tag组件

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com