简述
tag组件是开发过程中经常用到的,而它也相对简单,我们直接分析。
参数
| 参数 | 说明 | 类型 | 可选值 | 默认值 |
|---|---|---|---|---|
| type | 类型 | string | success/info/warning/danger | — |
| closable | 是否可关闭 | boolean | — | false |
| disable-transitions | 是否禁用渐变动画 | boolean | — | false |
| hit | 是否有边框描边 | boolean | — | false |
| color | 背景色 | string | — | — |
| size | 尺寸 | string | medium / small / mini | — |
| effect | 主题 | string | dark / light / plain | light |
hit、color、size、effect、type
- hit、size、effect、type通过控制class设置不同的样式
- color直接用style属性设置中标签上
props: {
type: String,
hit: Boolean,
color: String,
size: String,
effect: {
type: String,
default: 'light',
validator(val) {
return ['dark', 'light', 'plain'].indexOf(val) !== -1;
}
}
}
computed: {
tagSize() {
return this.size || (this.$ELEMENT || {}).size;
}
},
const classes = [
'el-tag',
type ? `el-tag--${type}` : '',
tagSize ? `el-tag--${tagSize}` : '',
effect ? `el-tag--${effect}` : '',
hit && 'is-hit'
];
const tagEl = (
<span
class={ classes }
style={{ backgroundColor: this.color }}>
...
</span>
);
closable
是否展示删除的按钮,删除的icon会出现在内容之后。
props: {
closable: Boolean,
},
const tagEl = (
<span>
{ this.$slots.default }
{
this.closable && <i class="el-tag__close el-icon-close" on-click={ this.handleClose }></i>
}
</span>
);
disable-transitions
动画的实现方法:使用transition组件嵌套一层。
props: {
disableTransitions: Boolean,
},
...
return this.disableTransitions ? tagEl : <transition name="el-zoom-in-center">{ tagEl }</transition>;
事件close、click
分别绑定给关闭的icon、组件根元素span
const tagEl = (
<span
on-click={ this.handleClick }>
{ this.$slots.default }
{
this.closable && <i class="el-tag__close el-icon-close" on-click={ this.handleClose }></i>
}
</span>
);
methods: {
handleClose(event) {
event.stopPropagation();
this.$emit('close', event);
},
handleClick(event) {
this.$emit('click', event);
}
},
全部源码(不含样式)
<script>
export default {
name: 'ElTag',
props: {
text: String,
closable: Boolean,
type: String,
hit: Boolean,
disableTransitions: Boolean,
color: String,
size: String,
effect: {
type: String,
default: 'light',
validator(val) {
return ['dark', 'light', 'plain'].indexOf(val) !== -1;
}
}
},
methods: {
handleClose(event) {
event.stopPropagation();
this.$emit('close', event);
},
handleClick(event) {
this.$emit('click', event);
}
},
computed: {
tagSize() {
return this.size || (this.$ELEMENT || {}).size;
}
},
render(h) {
const { type, tagSize, hit, effect } = this;
const classes = [
'el-tag',
type ? `el-tag--${type}` : '',
tagSize ? `el-tag--${tagSize}` : '',
effect ? `el-tag--${effect}` : '',
hit && 'is-hit'
];
const tagEl = (
<span
class={ classes }
style={{ backgroundColor: this.color }}
on-click={ this.handleClick }>
{ this.$slots.default }
{
this.closable && <i class="el-tag__close el-icon-close" on-click={ this.handleClose }></i>
}
</span>
);
return this.disableTransitions ? tagEl : <transition name="el-zoom-in-center">{ tagEl }</transition>;
}
};
</script>