vue实现环形进度组件
实现环形进度组件的步骤
使用SVG和Vue实现环形进度条
在Vue中,可以通过SVG的<circle>元素结合计算属性动态调整stroke-dasharray和stroke-dashoffset来实现环形进度效果。
<template>
<div class="circle-progress">
<svg width="120" height="120" viewBox="0 0 120 120">
<circle
class="progress-bg"
cx="60"
cy="60"
:r="radius"
stroke-width="10"
/>
<circle
class="progress-bar"
cx="60"
cy="60"
:r="radius"
stroke-width="10"
:stroke-dasharray="circumference"
:stroke-dashoffset="dashOffset"
/>
</svg>
<div class="progress-text">{{ progress }}%</div>
</div>
</template>
<script>
export default {
props: {
progress: {
type: Number,
default: 0,
validator: value => value >= 0 && value <= 100
}
},
data() {
return {
radius: 50
}
},
computed: {
circumference() {
return 2 * Math.PI * this.radius
},
dashOffset() {
return this.circumference * (1 - this.progress / 100)
}
}
}
</script>
<style>
.circle-progress {
position: relative;
width: 120px;
height: 120px;
}
.progress-bg {
fill: none;
stroke: #eee;
}
.progress-bar {
fill: none;
stroke: #4CAF50;
stroke-linecap: round;
transform: rotate(-90deg);
transform-origin: 50% 50%;
transition: stroke-dashoffset 0.3s ease;
}
.progress-text {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
font-size: 20px;
font-weight: bold;
}
</style>
使用CSS变量实现动态颜色
可以通过CSS变量让进度条颜色根据进度值动态变化:
watch: {
progress(newVal) {
const hue = Math.floor(newVal * 1.2)
this.$el.style.setProperty('--progress-color', `hsl(${hue}, 80%, 50%)`)
}
}
添加动画效果
在CSS中为进度条添加过渡效果:
.progress-bar {
transition: stroke-dashoffset 0.5s cubic-bezier(0.65, 0, 0.35, 1);
}
实现多色环形进度条
通过多个<circle>叠加可以实现分段颜色效果:
<circle
v-for="(segment, index) in segments"
:key="index"
class="progress-segment"
cx="60"
cy="60"
:r="radius"
stroke-width="10"
:stroke-dasharray="circumference"
:stroke-dashoffset="getSegmentOffset(index)"
:stroke="segment.color"
/>
响应式尺寸调整
通过计算属性使组件适应不同尺寸:
computed: {
viewBoxSize() {
const size = this.radius * 2 + this.strokeWidth
return `0 0 ${size} ${size}`
}
}
注意事项
- SVG的
viewBox需要与组件尺寸匹配 stroke-dasharray和stroke-dashoffset的计算基于圆的周长- 进度条从顶部开始需要旋转-90度
- 文本居中可以使用绝对定位配合transform
- 过渡效果应加在
stroke-dashoffset属性上







