移动端 tag 标签简单封装记录

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这样的英文色值,暂时未解决。

  • 8
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值