先看效果
话不多说,直接上代码
定义组件 scheduleChart.vue
<template>
<div class="progress-bar">
<div v-for="(item, index) in progressItems" :key="index" class="parallelogram"
:style="{ backgroundColor: item.color, boxShadow: item.shadow }">
</div>
<div style="margin-left: 5px;">
<div :style="{ color: props.bgcolor }">{{ percentage }}</div>
<div>{{ props.textDescription }}</div>
</div>
</div>
</template>
<script setup lang="ts">
import { ref, watch } from 'vue';
const props = defineProps({
percentage: {
type: Number,
required: true,
default: 0
},
textDescription: {
type: String,
default: '百分比(%)'
},
bgcolor: {
type: String,
default: '#4CAF50'
}
});
const progressItems = ref<Array<{ color: string; shadow: string }>>([]);
// 更新进度条项目数组
const updateProgress = (percentage: number) => {
const totalItems = 20;
const filledItems = Math.ceil((percentage / 100) * totalItems);
// 清空当前的进度条项目
progressItems.value = [];
// 生成新的进度条项目数组
for (let i = 0; i < filledItems; i++) {
progressItems.value.push({ color: props.bgcolor, shadow: '0 0 5px ' + props.bgcolor });
}
for (let i = 0; i < totalItems - filledItems; i++) {
progressItems.value.push({ color: '#f0f0f0', shadow: 'none' });
}
}
// 使用 watch 监听 props.percentage 的变化
watch(() => props.percentage, (newVal) => {
updateProgress(newVal);
}, { immediate: true }); // immediate 选项确保初始化时立即执行一次
</script>
<style scoped>
.progress-bar {
width: 400px;
display: flex;
flex-wrap: wrap;
align-items: end;
justify-content: start;
}
.parallelogram {
width: 11px;
height: 22px;
transform: skew(-10deg);
margin: 2px;
}
</style>
在父组件调用
<template>
<div>
<scheduleChart :percentage="23" />
<scheduleChart :percentage="55" :bgcolor="'#FFD62F'" :textDescription="'进度(%)'" />
</div>
</template>
<script setup lang="ts">
import { ref, onMounted, reactive, watch } from 'vue'
import scheduleChart from './components/scheduleChart.vue'
</script>
<style lang="scss" scoped></style>