Vue 渐变色百分比率条组件

最近项目中需要用到百分条,自己写了一个组件,记录下来。
代码地址
1,实现效果:
在这里插入图片描述
2, 代码

<template>
  <div class="progress-main">
    <div class="progress-bg">
      <div class="progress-bar" :style="barStyle"></div>
    </div>
  </div>
</template>

<script lang="ts">
import { Component, Vue, Watch, Prop } from "vue-property-decorator";
@Component({})
export default class MyProgress extends Vue {

  // 进度条 的百分比 [0-1] 的小数
  @Prop({}) percent
  percentage = 0;
  barStyle = {};
  // 进度条 每个阶段的 颜色组
  linearColors = [
    { v: 33, s: "#ff1026", e: "#a32f71" },
    { v: 66, s: "#a32f72", e: "#6145a5" },
    { v: 90, s: "#6145a5", e: "#0864ee" },
    { v: 100, s: "#0864ee", e: "#0864ee" }
  ];
  @Watch('percent')
  update(val) {
    this.percentage = val;
    var color = this.getGradient;
    var w = this.getPercentage;
    this.barStyle = {
      backgroundImage: color,
      width: w + "%"
    };
  }

  // 通过比例 获取 百分比
  get getPercentage() {
    if (!this.percentage || this.percentage < 0.01) {
      return 0;
    } else if (this.percentage >= 1) {
      return 100;
    } else {
      return this.percentage * 100;
    }
  }
  // 获取 进度条颜色对象
  get getGradient() {
    let linecolor = this.getColorItem(this.percentage); //[]
    let colors = ''
    for(let sub of linecolor) {
        colors += ',' + sub.s + ',' + sub.e;
    }
    if (linecolor.length) {
      return "linear-gradient(90deg" + colors + ")";
    } else {
      return "";
    }
  }
  // 根据进度 获取颜色数组
  getColorItem(p) {
    let mp = this.getPercentage; //40
    let colorArray = []
    colorArray.push(this.linearColors[0])
    for (let i = 1; i < this.linearColors.length - 1; i ++) {
      if (mp >= this.linearColors[i].v && mp <= this.linearColors[i+1].v ) {
        colorArray.push(this.linearColors[i])
      } 
    }
    return colorArray;
  }
  mounted() {
    this.percentage = this.percent;
    var color = this.getGradient;
    var w = this.getPercentage;
    this.barStyle = {
      backgroundImage: color,
      width: w + "%"
    };
  }
}
</script>

<style lang="scss">
.progress-main {
  display: flex;
  .progress-bg {
    width: 50px;
    background: #eaedf4;
    flex: 1;
    margin: 8px 0;
    border-radius: 4px;
    .progress-bar {
      height: 8px;
      border-radius: 4px;
    }
  }
}
</style>

3,使用

//引入组件
import MyProgress from "./components/Progress.vue";
//注册
@Component({
  components: {
    MyProgress
  }
})
//使用
<my-progress style="width:320px" :percent="0.9"></my-progress>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值