ElementUI的进度条百分比自定义不够灵活,重新实现一下
最终效果
<template>
<div class="progress-container">
<div class="progress-bar-wrapper">
<div
class="progress-bar"
:style="{
width: `${validPercentage}%`,
backgroundColor: getProgressColor(validPercentage)
}"
></div>
<span
class="percentage-text"
:class="{ 'light-text': shouldTextBeLight }"
:style="textPositionStyle"
>
{{ validPercentage }}%
</span>
</div>
</div>
</template>
<script>
export default {
name: 'CustomProgress',
props: {
percentage: {
type: [Number, String],
default: 0
}
},
computed: {
validPercentage() {
const value = Number(this.percentage);
return Math.min(Math.max(0, value), 100);
},
shouldTextBeLight() {
// 完全内部时才使用白色
return this.validPercentage >= 52;
},
textPositionStyle() {
const textWidth = 12; // 文字宽度百分比(包含安全边距)
let position;
if (this.validPercentage >= 52) {
// 进度较大时,文字在进度条内部靠左
position = Math.min(this.validPercentage - textWidth, 88);
} else if (this.validPercentage <= 48) {
// 进度较小时,文字在进度条外部靠右
position = Math.max(this.validPercentage + textWidth, 12);
} else {
// 在边界区域时,强制推向更近的一边
position = (this.validPercentage < 50) ? 75 : 25;
}
return {
left: `${position}%`,
};
}
},
methods: {
getProgressColor(value) {
if (value >= 90) {
return 'var(--danger-color, #F56C6C)';
} else if (value >= 70) {
return 'var(--warning-color, #E6A23C)';
}
return 'var(--success-color, #67C23A)';
}
}
}
</script>
<style scoped>
.progress-container {
width: 100%;
}
.progress-bar-wrapper {
position: relative;
height: 20px;
background-color: var(--el-fill-color-light, #ebeef5);
overflow: hidden;
}
.progress-bar {
position: absolute;
left: 0;
top: 0;
height: 100%;
width: 0;
transition: width 0.3s ease-in-out, background-color 0.3s ease-in-out;
}
.percentage-text {
position: absolute;
top: 50%;
transform: translate(-50%, -50%);
font-size: 12px;
font-family: var(--el-font-family, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif);
white-space: nowrap;
z-index: 1;
pointer-events: none;
color: var(--el-text-color-regular, #606266);
transition: all 0.3s ease-in-out;
padding: 0 4px;
user-select: none;
}
.percentage-text.light-text {
color: #ffffff;
}
</style>
使用时传入percentage即可