想要实现一种渐变图例,并展示该值,效果图如下:
后台接口形式:
颜色的格式:
数值的格式:
代码片段:
<template>
<div class="legends">
<div class="legend" v-for="(item, index) in legends" :key="index">
<!-- <div class="name">
{{ item.name }}<span v-if="item.unit != ''">({{ item.unit }})</span>
</div> -->
<div class="name">{{ item.name }}<span>(单位: )</span></div>
<div
class="bar"
:style="{
background: 'linear-gradient(to right,' + item.bgColors + ')',
}"
>
<div class="number">
<p v-for="(i, idx) in item.value" :key="idx">{{ i }}</p>
</div>
</div>
</div>
</div>
</template>
<script>
export default {
props: {
legendData: {
type: Object,
default: function () {
return {};
},
},
},
mounted() {
console.log(this.legendData);
this.createLegend(this.legendData);
},
data() {
return {
legends: [
{
name: '',
unit: '',
bgColors: '',
value: [0, 7.5, 15, 22.5, 30],
},
],
};
},
methods: {
createLegend(info) {
this.legends = [];
let bgColors = info.rgbacolors;
let values = info.values;
if (!bgColors) return;
let arr = [];
for (let i = 0; i < bgColors.length; i++) {
let color = bgColors[i];
arr.push(`rgb(${color[0]},${color[1]},${color[2]})`);
}
let bgColorsText = arr.join(',');
let endValue =
values.length > bgColors.length
? values[values.length - 2]
: values[values.length - 1];
let numValue = [];
if (bgColors.length < 5) {
numValue = [
values[0],
values[parseInt((values.length - 1) / 2)],
endValue,
];
} else if (bgColors.length == 6) {
numValue = [
values[0],
values[1],
values[2],
values[3],
values[4],
values[5],
];
} else if (bgColors.length == 5 || bgColors.length > 6) {
numValue = [
values[0],
values[parseInt((values.length - 1) / 2 / 2)],
values[parseInt((values.length - 1) / 2)],
values[
parseInt(
(values.length - 1 - (values.length - 1) / 2) / 2 +
(values.length - 1) / 2,
)
],
endValue,
];
}
this.legends.push({
name: name,
unit: info.unit || '',
bgColors: bgColorsText,
value: numValue,
});
},
},
};
</script>
<style lang="scss" scoped>
// .legends {
// position: absolute;
// right: 28rem;
// top: 10rem;
// width: auto;
// height: 80%;
// }
.legends {
position: absolute;
z-index: 99;
bottom: 110px;
left: 28px;
.legend {
padding: 4px;
border-radius: 2px;
.name {
padding-left: 1px;
margin-bottom: 4px;
font-size: 12px;
color: #fff;
text-shadow: 0 0 3px #000;
}
.bar {
width: 280px;
position: relative;
height: 14px;
border-radius: 10px;
box-shadow: 0 0 4px #252525;
.number {
display: flex;
align-items: center;
justify-content: space-between;
position: absolute;
left: 0;
right: 0px;
top: 1px;
padding: 0 5px;
box-sizing: border-box;
p {
font-size: 12px;
color: #fff;
// width: 80px;
text-align: center;
text-shadow: -1px 1px #000;
line-height: 1;
}
p:nth-child(1) {
text-align: left;
}
p:nth-child(3) {
text-align: right;
}
}
}
}
}
</style>