vue实现进度条
Vue 实现进度条的方法
使用原生 HTML 和 CSS 结合 Vue 数据绑定
创建一个简单的进度条,通过 Vue 的数据绑定动态控制进度值。
<template>
<div class="progress-container">
<div class="progress-bar" :style="{ width: progress + '%' }"></div>
</div>
<button @click="increaseProgress">增加进度</button>
</template>
<script>
export default {
data() {
return {
progress: 0
}
},
methods: {
increaseProgress() {
if (this.progress < 100) {
this.progress += 10
}
}
}
}
</script>
<style>
.progress-container {
width: 100%;
height: 20px;
background-color: #e0e0e0;
border-radius: 10px;
overflow: hidden;
}
.progress-bar {
height: 100%;
background-color: #42b983;
transition: width 0.3s ease;
}
</style>
使用第三方组件库
Vue 生态中有许多现成的 UI 组件库提供了进度条组件,例如 Element UI、Vuetify 等。
以 Element UI 为例:
<template>
<el-progress :percentage="progress"></el-progress>
<el-button @click="increaseProgress">增加进度</el-button>
</template>
<script>
export default {
data() {
return {
progress: 0
}
},
methods: {
increaseProgress() {
if (this.progress < 100) {
this.progress += 10
}
}
}
}
</script>
实现环形进度条
通过 SVG 和 Vue 结合,可以创建环形进度条。
<template>
<div class="circular-progress">
<svg viewBox="0 0 36 36">
<path
d="M18 2.0845
a 15.9155 15.9155 0 0 1 0 31.831
a 15.9155 15.9155 0 0 1 0 -31.831"
fill="none"
stroke="#e0e0e0"
stroke-width="2"
/>
<path
d="M18 2.0845
a 15.9155 15.9155 0 0 1 0 31.831
a 15.9155 15.9155 0 0 1 0 -31.831"
fill="none"
stroke="#42b983"
stroke-width="2"
:stroke-dasharray="`${progress}, 100`"
/>
</svg>
<span>{{ progress }}%</span>
</div>
<button @click="increaseProgress">增加进度</button>
</template>
<script>
export default {
data() {
return {
progress: 0
}
},
methods: {
increaseProgress() {
if (this.progress < 100) {
this.progress += 10
}
}
}
}
</script>
<style>
.circular-progress {
position: relative;
width: 100px;
height: 100px;
}
.circular-progress svg {
width: 100%;
height: 100%;
}
.circular-progress span {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
font-size: 16px;
}
</style>
动画效果增强
为进度条添加平滑的动画效果,提升用户体验。
<template>
<div class="progress-container">
<div class="progress-bar" :style="{ width: animatedProgress + '%' }"></div>
</div>
<input type="range" v-model="progress" min="0" max="100">
</template>
<script>
export default {
data() {
return {
progress: 0,
animatedProgress: 0
}
},
watch: {
progress(newVal) {
const animate = () => {
if (this.animatedProgress < newVal) {
this.animatedProgress += 1
requestAnimationFrame(animate)
} else if (this.animatedProgress > newVal) {
this.animatedProgress -= 1
requestAnimationFrame(animate)
}
}
animate()
}
}
}
</script>
这些方法提供了从简单到复杂的进度条实现方案,可以根据项目需求选择合适的方式。







