vue3实现环形进度条组件

908 阅读1分钟

vue3实现环形进度条组件在pc后台系统尤为常见统计数据面板,有时候简单的组件使用框架不满足或者改样式起来费劲还不如自己手写一个~接下来步骤上干货

效果演示

代码实现

创建 ProgressCircle.vue 组件 代码如下:

<template>
  <div
    :style="{ width: size + 'px', height: size + 'px' }"
    class="progress-circle"
  >
    <svg :width="size" :height="size" viewBox="0 0 100 100">
      <circle
        class="background"
        cx="50"
        cy="50"
        r="45"
        stroke-width="5"
        fill="none"
      />
      <circle
        class="progress"
        cx="50"
        cy="50"
        r="45"
        stroke-width="5"
        :stroke="color"
        fill="none"
        stroke-dasharray="282"
        :stroke-dashoffset="282 - (computedProgress / 100) * 282"
        style="transition: stroke-dashoffset 0.6s"
      />
    </svg>
    <div class="text" :style="{ fontSize: size / 5 + 'px' }">{{ text }}</div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'

const props = defineProps<{
  progress?: number
  color?: string
  size?: number
  text?: string
  duration?: number
}>()

// 设置默认值
const defaultProgress = 50
const defaultColor = 'red'
const defaultSize = 100
const defaultDuration = 500
const defaultText = '50%' // 默认文案

const computedProgress = ref(0)
const color = ref(props.color ?? defaultColor) // 使用传入的颜色或默认颜色
const size = ref(props.size ?? defaultSize) // 使用传入的大小或默认大小
const text = ref(props.text ?? defaultText) // 使用传入的文本或默认文本

onMounted(() => {
  setTimeout(() => {
    computedProgress.value = props.progress ?? defaultProgress
  }, props.duration ?? defaultDuration)
})
</script>

<style scoped>
.progress-circle {
  display: flex;
  justify-content: center;
  align-items: center;
  position: relative;
}

svg {
  transform: rotate(-90deg);
}

circle.background {
  stroke: #eee;
}

circle.progress {
  stroke-linecap: round;
  transition: stroke-dashoffset 0.8s ease;
}

.text {
  position: absolute;
  font-weight: bold;
}
</style>

组件调用

<template>
  <div class="app">
    <ProgressCircle :progress="50" />
    <ProgressCircle :progress="30" color="orange" text="30%" />
    <ProgressCircle :progress="85" color="green" text="85%" />
  </div>
</template>

<script setup>
import ProgressCircle from './components/ProgressCircle.vue'
</script>

说明

  • stroke-dasharray 设置为圆周长(大约 282),以支持饱满的进度绘制。
  • stroke-dashoffset 动态计算,以显示特定进度(computedProgress 为当前进度百分比)。
  • stroke-linecap 属性用于设置圆角效果,使进度开始和结束位置更圆滑。

总结

实现起来并不难,这样就很简单的实现了带动画效果的环形进度条了,有需要的朋友可以基于此自己二次开发或者设计,兴许哪天你也用上了。并且可以扩展成自己想要的风格了