vue实现环形进度组件
实现环形进度组件
环形进度组件可以通过SVG或Canvas实现,以下是基于SVG的实现方法:
定义组件模板
<template>
<div class="circle-progress">
<svg :width="size" :height="size" viewBox="0 0 100 100">
<circle
cx="50"
cy="50"
:r="radius"
fill="none"
:stroke="backgroundColor"
:stroke-width="strokeWidth"
/>
<circle
cx="50"
cy="50"
:r="radius"
fill="none"
:stroke="progressColor"
:stroke-width="strokeWidth"
:stroke-dasharray="dashArray"
:stroke-dashoffset="dashOffset"
stroke-linecap="round"
/>
<text
x="50"
y="50"
text-anchor="middle"
dominant-baseline="middle"
:fill="textColor"
>
{{ progress }}%
</text>
</svg>
</div>
</template>
定义组件逻辑
<script>
export default {
props: {
progress: {
type: Number,
default: 0,
validator: value => value >= 0 && value <= 100
},
size: {
type: Number,
default: 200
},
strokeWidth: {
type: Number,
default: 10
},
backgroundColor: {
type: String,
default: '#eee'
},
progressColor: {
type: String,
default: '#42b983'
},
textColor: {
type: String,
default: '#333'
}
},
computed: {
radius() {
return 50 - this.strokeWidth / 2
},
circumference() {
return 2 * Math.PI * this.radius
},
dashArray() {
return this.circumference
},
dashOffset() {
return this.circumference * (1 - this.progress / 100)
}
}
}
</script>
添加样式
<style scoped>
.circle-progress {
display: inline-block;
position: relative;
}
.circle-progress circle {
transition: stroke-dashoffset 0.5s ease;
}
</style>
使用组件示例
<template>
<div>
<circle-progress :progress="75" />
</div>
</template>
<script>
import CircleProgress from './CircleProgress.vue'
export default {
components: {
CircleProgress
}
}
</script>
自定义选项说明
- progress:进度值,范围0-100
- size:组件大小,单位为px
- strokeWidth:圆环宽度
- backgroundColor:背景圆环颜色
- progressColor:进度圆环颜色
- textColor:文本颜色
动画效果
组件已经内置了过渡动画,当progress值变化时会有平滑的动画效果。可以通过调整CSS中的transition属性来修改动画时长和缓动函数。







