vue项目之数量占比进度条实现
vue项目之数量占比进度条实现
功能说明:
1、点击开始,滚动条自动加;
2、点击停止,滚动条停止加;
封装如下
<template>
<div>
<div class="progress-bar">
<div
class="progress"
:style="{
width: progressRatio + '%'
}"
>
{{ surplusProgress }}
</div>
{{ totalProgress }}
</div>
{{ surplusProgress }}
<button @click="start()">开始</button>
<button @click="stop()">停止</button>
</div>
</template>
<script>
export default {
name: 'index',
components: {},
props: {
total: {
type: Number
},
surplus: {
type: Number
}
},
data() {
return {
totalProgress: 0,
surplusProgress: 0,
progressRatio: 0,
clearInt: null // 定时器名
}
},
computed: {
// 用于监听两个值同时存在的情况
progress() {
const { surplus, total } = this
return {
surplus,
total
}
}
},
watch: {
progress(newVal) {
this.totalProgress = newVal.total
this.surplusProgress = newVal.surplus
// 注意这里是当前剩余的值比上总值的一个比例显示
this.progressRatio = (newVal.surplus / newVal.total) * 100
}
},
methods: {
start() {
let _this = this
// 增加的值 = 总数量 / 100
let addNum = _this.totalProgress / 100
clearInterval(_this.clearInt)
_this.clearInt = setInterval(function () {
_this.progressRatio = _this.progressRatio + 1
// 这里剩余的值 必须按照比例去增加 才可以最终到达总值
_this.surplusProgress = ((_this.surplusProgress * 100 + addNum * 100) / 100).toFixed(1)
if (_this.progressRatio >= 100) {
clearInterval(_this.clearInt)
_this.progressRatio = _this.progressRatio
_this.surplusProgress = parseInt(_this.surplusProgress)
}
}, 100)
},
stop() {
clearInterval(this.clearInt)
}
}
}
</script>
<style lang="scss" scoped>
.progress-bar {
width: 500px;
height: 30px;
color: #000;
text-align: center;
line-height: 30px;
box-sizing: border-box;
margin-top: 50px;
margin-bottom: 20px;
border: 1px solid gray;
box-shadow: -1px -1px 1px #000;
background: rgb(177, 174, 174);
position: relative;
.progress {
height: 100%;
background: #3165c5;
color: #fff;
overflow: hidden;
position: absolute;
opacity: 0.5;
text-align: center;
}
}
</style>
组件使用
<template>
<div class="content-box">
<div class="container">
<Progress :total="total1" :surplus="surplus1" />
<Progress :total="total2" :surplus="surplus2" />
</div>
</div>
</template>
<script>
import Progress from '@/components/ProgressBar'
export default {
name: 'record',
components: {
Progress
},
data() {
return {
surplus1: 0,
total1: 0,
surplus2: 0,
total2: 0
}
},
activated() {
let _this = this
// 模拟请求情况
setTimeout(() => {
_this.surplus1 = 30
_this.total1 = 100
_this.surplus2 = 60
_this.total2 = 220
}, 3000)
},
methods: {},
mounted() {}
}
</script>
<style scoped>
</style>
效果如下
遇到问题
在到达终点时,总数和剩余值不一致问题,查明问题原因是小数点的问题,目前保留一位小数点;