vue实现圆环进度
Vue 实现圆环进度的方法
使用 SVG 实现圆环进度
SVG 是实现圆环进度的常用方法,通过 stroke-dasharray 和 stroke-dashoffset 属性可以轻松控制进度条的显示。
<template>
<div class="progress-ring">
<svg width="120" height="120">
<circle
class="progress-ring__background"
stroke="#eee"
stroke-width="10"
fill="transparent"
r="50"
cx="60"
cy="60"
/>
<circle
class="progress-ring__circle"
stroke="#4CAF50"
stroke-width="10"
fill="transparent"
r="50"
cx="60"
cy="60"
:stroke-dasharray="circumference"
:stroke-dashoffset="offset"
/>
</svg>
</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;
},
offset() {
return this.circumference - (this.progress / 100) * this.circumference;
}
}
};
</script>
<style>
.progress-ring {
display: inline-block;
}
.progress-ring__circle {
transition: stroke-dashoffset 0.35s;
transform: rotate(-90deg);
transform-origin: 50% 50%;
}
</style>
使用 Canvas 实现圆环进度
Canvas 也可以用于绘制圆环进度,适合需要动态渲染的场景。
<template>
<div class="progress-ring">
<canvas ref="canvas" width="120" height="120"></canvas>
</div>
</template>
<script>
export default {
props: {
progress: {
type: Number,
default: 0,
validator: value => value >= 0 && value <= 100
}
},
mounted() {
this.drawProgress();
},
watch: {
progress() {
this.drawProgress();
}
},
methods: {
drawProgress() {
const canvas = this.$refs.canvas;
const ctx = canvas.getContext('2d');
const centerX = canvas.width / 2;
const centerY = canvas.height / 2;
const radius = 50;
const startAngle = -Math.PI / 2;
const endAngle = startAngle + (2 * Math.PI * this.progress / 100);
ctx.clearRect(0, 0, canvas.width, canvas.height);
// 绘制背景圆环
ctx.beginPath();
ctx.arc(centerX, centerY, radius, 0, 2 * Math.PI);
ctx.strokeStyle = '#eee';
ctx.lineWidth = 10;
ctx.stroke();
// 绘制进度圆环
ctx.beginPath();
ctx.arc(centerX, centerY, radius, startAngle, endAngle);
ctx.strokeStyle = '#4CAF50';
ctx.lineWidth = 10;
ctx.stroke();
}
}
};
</script>
使用 CSS 实现圆环进度
CSS 的 conic-gradient 可以用于实现圆环进度,但兼容性较差。
<template>
<div class="progress-ring">
<div class="progress-ring__container">
<div class="progress-ring__fill" :style="{ '--progress': progress }"></div>
</div>
</div>
</template>
<style>
.progress-ring__container {
width: 120px;
height: 120px;
border-radius: 50%;
background: conic-gradient(#4CAF50 calc(var(--progress) * 3.6deg), #eee 0deg);
display: flex;
align-items: center;
justify-content: center;
}
.progress-ring__fill {
width: 100px;
height: 100px;
background: white;
border-radius: 50%;
}
</style>
使用第三方库(如 Vuetify)
如果项目中使用了 Vuetify,可以直接使用其内置的 v-progress-circular 组件。
<template>
<v-progress-circular
:value="progress"
:size="120"
:width="10"
color="primary"
>
{{ progress }}%
</v-progress-circular>
</template>
<script>
export default {
props: {
progress: {
type: Number,
default: 0,
validator: value => value >= 0 && value <= 100
}
}
};
</script>
以上方法可以根据项目需求选择适合的实现方式。SVG 和 Canvas 适合自定义需求,而第三方库可以快速集成。




