前言
最近仪表写得贼多,已经伤了......业务总能提出一些想当然的需求,只要他想得到,咱就尽量满足。
一、需求:能否写一个渐变色儿的仪表盘?
安排!上代码!
<template>
<div class="echartGuage">
<MyChart :op="op" :height="'100%'" @chart-click="chartClick"></MyChart>
</div>
</template>
<script>
import MyChart from '@/components/MyChart.vue'
import * as echarts from 'echarts'
export default {
components: {
MyChart
},
props: {
// 默认数据,可以从接口获取
gaugeData: {
type: Object,
default: () => {
return {
rate: 60,
unit: '%',
total: 100,
color: 'red' // 可以通过从接口获取不同颜色来映射仪表盘亮灯
}
}
}
},
data () {
return {}
},
computed: {
op () {
return {
series: [
// series[0] 用来展示仪表盘进度条等(外环)
{
type: 'gauge',
data: [{ value: this.gaugeData.rate }],
startAngle: 180,
endAngle: 0,
spliteLine: {
show: false
},
axisTick: {
show: false
},
axisLabel: {
show: false
},
radius: 92,
center: ['50%', '50%'],
detail: {
show: false,
},
pointer: {
show: true // 展示指针
},
axisLine: {
show: true,
lineStyle: {
width: 10,
color: [
[
this.gaugeData.rate / this.gaugeData.total,
new echarts.graphic.LinearGradient(0, 0, 1, 0, [
{ offset: 0.1, color: '#009fff' },
{ offset: 1, color: '#02fdde' }
])
],
[1, 'rgba(67,147,255,0.30)']
]
}
}
},
// series[1] 表示内环
{
type: 'gauge',
startAngle: 180,
endAngle: 0,
spliteLine: {
show: false
},
axisTick: {
show: true,
length: 3,
splitNumber: 2,
lineStyle: {
color: '#000000',
width: 0.2
}
},
axisLabel: {
show: false
},
radius: 82,
center: ['50%', '50%'],
detail: {
show: false
},
pointer: {
show: false
},
axisLine: {
show: true,
lineStyle: {
width: 8,
color: [
[
1,
new echarts.graphic.LinearGradient(0, 0, 1, 0, [
{ offset: 0.1, color: '#c31425' },
{ offset: 0.2, color: '#e15128' },
{ offset: 0.5, color: '#e4d74e' },
{ offset: 0.75, color: '#94d678' },
{ offset: 0.9, color: '#63d692' }
])
],
[1, 'rgba(67,147,255,0.30)']
]
}
}
}
]
}
}
},
methods: {
chartClick (params) {}
}
}
</script>
<style lang="less" scoped>
.echartGuage {
position: relative;
width: 400px;
height: 300px;
}
</style>
二、优化:不想要指针,能否加个百分比?
这个嘛,也不是不可以,见 detail
detail: {
show: true,
formatter: `{value}${this.gaugeData.unit}`,
fontSize: 24,
fontWeight: 'bolder',
color: '#ccc',
offsetCenter: [0, -20]
},
pointer: {
show: false // 不展示指针
},
三、再优化:仪表盘中间的百分比单位能否小一点?
额,有点难度,结合 title 采用 rich 富文本,如下!
// title 与 series 同级,series[0] 里面的 detail 不展示
title: {
show: true,
top: '120',
left: 'center',
text: `{rate|${this.gaugeData.rate}} {unit|${this.gaugeData.unit}}`,
textStyle: {
color: '#cccccc',
rich: {
rate: {
fontSize: 24
},
unit: {
fontsize: 16
}
}
},