vue element-ui progress环形进度条组件自定义文字和颜色

ps: 本文只讨论环形进度条,不包括直线进度条,但是原理是一样的, 用elementUI的el-progress将环形进度条渲染出来然后打开F12复制代码自己改参数即可

el-progress 进度条组件的局限性

  1. 这个组件不能做颜色渐变
  2. 文字不能换行
  3. 进度条不能改变粗细

接下来围绕以上三个问题封装一个进度条组件, 实现全方位自定义, 达到下图的效果。

组件内容

<template>
  <div class="el-progress el-progress--circle">
    <div class="el-progress-circle" style="height: 200px; width: 200px;">
      <svg viewBox="0 0 100 100">
        <!--定义渐变-->
        <defs>
          <linearGradient :id="colorId" x1="0" y1="0" x2="1" y2="1">
            <stop offset="0%" :style="`stop-color:${shade[0]}`" stop-opacity="0.8"></stop>
            <stop offset="100%" :style="`stop-color:${shade[1]}`" stop-opacity="1"></stop>
          </linearGradient>
        </defs>
        <!--
          第1个path是灰色的背景环形
          stroke-width: 进度条的宽细
          stroke:颜色
        -->
        <path d="
        M 50 50
        m 0 -47
        a 47 47 0 1 1 0 94
        a 47 47 0 1 1 0 -94
        " stroke="#e5e9f2" stroke-width="2" fill="none" class="el-progress-circle__track"
              style="stroke-dasharray: 295.31px, 295.31px; stroke-dashoffset: 0px;"></path>

        <!--
          第1个path是灰色的背景环形
          stroke-width: 进度条的宽细
          stroke:颜色
        -->
        <path d="
        M 50 50
        m 0 -47
        a 47 47 0 1 1 0 94
        a 47 47 0 1 1 0 -94
        " :stroke="`url(#${colorId})`" fill="none" stroke-linecap="round" stroke-width="4.8"
              class="el-progress-circle__path"
              :style="`stroke-dasharray: ${calcProgress()}px, 295.31px; stroke-dashoffset: 0px; transition: stroke-dasharray 0.6s ease 0s, stroke 0.6s ease 0s;`"></path>
      </svg>
    </div>
    <div class="el-progress__text" :style="'color:'+shade[1]">
      <span class="percentage">{{ percentage }}</span>
      <i class="fa fa-percent" aria-hidden="true"></i>
      <br/>
      <span class="abstract">{{ abstract }}</span>
      <span class="abstract-unit">单</span>
    </div>
  </div>
</template>

<script>
export default {
  name: "CircleProgress",
  props: {
    //百分比
    percentage: {
      type: String,
      default: '-'
    },
    //摘要
    abstract: {
      type: String,
      default: '-'
    },
    //渐变
    shade: {
      type: Array,
      default: ['white', "black"],
    }
  },
  data() {
    return {
      //svg渐变的id,需要保证唯一否则颜色会重复
      colorId: null,
    }
  },
  created() {
    this.colorId = 'colorful-' + crypto.randomUUID();
  },
  methods: {
    calcProgress() {
      //百分之一的值等于svg的stroke-dasharray的2.9531
      return this.percentage * 2.9531
    }
  }


}
</script>

<style scoped>
.percentage {
  font-size: 50px;
  font-weight: bold;
}
.abstract {
  font-size: 30px;
}
.abstract-unit {
  font-size: 20px;
}
</style>

调用组件

<circle-progress percentage="23"
                           abstract="2"
                           shade="['#FB9955','#FE555C']"/>
  • percentage:百分比值
  • abstract: 摘要值
  • shade:渐变

完。

posted @ 2022-08-16 16:11  _戈多  阅读(5312)  评论(0编辑  收藏  举报