Vue自定义进度条

ElementUI的进度条百分比自定义不够灵活,重新实现一下

最终效果
在这里插入图片描述

<template>
  <div class="progress-container">
    <div class="progress-bar-wrapper">
      <div
        class="progress-bar"
        :style="{
          width: `${validPercentage}%`,
          backgroundColor: getProgressColor(validPercentage)
        }"
      ></div>
      <span
        class="percentage-text"
        :class="{ 'light-text': shouldTextBeLight }"
        :style="textPositionStyle"
      >
        {{ validPercentage }}%
      </span>
    </div>
  </div>
</template>

<script>
export default {
  name: 'CustomProgress',
  props: {
    percentage: {
      type: [Number, String],
      default: 0
    }
  },
  computed: {
    validPercentage() {
      const value = Number(this.percentage);
      return Math.min(Math.max(0, value), 100);
    },
    shouldTextBeLight() {
      // 完全内部时才使用白色
      return this.validPercentage >= 52;
    },
    textPositionStyle() {
      const textWidth = 12; // 文字宽度百分比(包含安全边距)
      let position;

      if (this.validPercentage >= 52) {
        // 进度较大时,文字在进度条内部靠左
        position = Math.min(this.validPercentage - textWidth, 88);
      } else if (this.validPercentage <= 48) {
        // 进度较小时,文字在进度条外部靠右
        position = Math.max(this.validPercentage + textWidth, 12);
      } else {
        // 在边界区域时,强制推向更近的一边
        position = (this.validPercentage < 50) ? 75 : 25;
      }

      return {
        left: `${position}%`,
      };
    }
  },
  methods: {
    getProgressColor(value) {
      if (value >= 90) {
        return 'var(--danger-color, #F56C6C)';
      } else if (value >= 70) {
        return 'var(--warning-color, #E6A23C)';
      }
      return 'var(--success-color, #67C23A)';
    }
  }
}
</script>

<style scoped>
.progress-container {
  width: 100%;
}

.progress-bar-wrapper {
  position: relative;
  height: 20px;
  background-color: var(--el-fill-color-light, #ebeef5);
  overflow: hidden;
}

.progress-bar {
  position: absolute;
  left: 0;
  top: 0;
  height: 100%;
  width: 0;
  transition: width 0.3s ease-in-out, background-color 0.3s ease-in-out;
}

.percentage-text {
  position: absolute;
  top: 50%;
  transform: translate(-50%, -50%);
  font-size: 12px;
  font-family: var(--el-font-family, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif);
  white-space: nowrap;
  z-index: 1;
  pointer-events: none;
  color: var(--el-text-color-regular, #606266);
  transition: all 0.3s ease-in-out;
  padding: 0 4px;
  user-select: none;
}

.percentage-text.light-text {
  color: #ffffff;
}
</style>

使用时传入percentage即可

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值