1、封装的组件代码
<template>
<span
:class="['tag-item', `tag-${type}`]"
:style="{ color, backgroundColor: hexToRgba(color, 0.07) }"
>
<slot></slot>
</span>
</template>
<script>
export default {
name: 'tag',
props: {
color: {
type: String,
default: ''
},
type: {
type: String,
default: 'primary'
}
},
data() {
return {};
},
methods: {
// 颜色值转换 hex 转成 rgba
hexToRgba(hex, alpha = 1) {
const result = /^#?([a-f\d]{1,2}){3}$/i.exec(hex);
if (result) {
const r = parseInt(result[1], 16);
const g = parseInt(result[2], 16);
const b = parseInt(result[3], 16);
return `rgba(${r},${g},${b},${alpha})`;
}
return hex;
}
}
};
</script>
<style scoped>
.tag-item {
padding: 0.02rem 0.06rem;
border-radius: 0.02rem;
font-size: 0.1rem;
}
.tag-primary {
color: rgba(44, 133, 255, 1);
background-color: rgba(44, 133, 255, 0.07);
border: 0.01rem rgba(44, 133, 255, 1) solid;
}
.tag-success {
color: rgba(83, 169, 82, 1);
background-color: rgba(83, 169, 82, 0.07);
border: 0.01rem rgba(83, 169, 82, 1) solid;
}
.tag-info {
}
.tag-warning {
color: rgba(255, 119, 15, 1);
background-color: rgba(255, 119, 15, 0.07);
border: 0.01rem rgba(255, 119, 15, 1) solid;
}
.tag-danger {
color: rgba(255, 74, 74, 1);
background-color: rgba(255, 74, 74, 0.07);
border: 0.01rem rgba(255, 74, 74, 1) solid;
}
</style>
2、组件使用
<template>
<div>
<tag>primary</tag>
<tag type="warning">warning</tag>
<tag type="danger">danger</tag>
<tag type="success">success</tag>
<tag color="#25C0E0">自定义颜色</tag>
</div>
</template>
<script>
// UI组件
import Tag from './tag.vue';
export default {
name: 'demo',
components: {
Tag
}
};
</script>
总结:在写tag组件时,以为会很简单,执行时发现其中涉及到了一些自己不曾想过的问题点,比如自定义颜色时,如何将hex转rgba的问题,参考了elementui源码,发现很晦涩难懂,上面的demo也只是解决了自定义颜色时将hex转换成rgba,至于传red、blue、green这样的英文色值,暂时未解决。