Project scenario:
When displaying a chart, sometimes the legend also needs to show some content, for example like this:
describe
Ordinary legends are generally just
But we want to display more information, so we need to use a thing: string template: formatter
solution:
directly on the code
Define an object in data(), you can set some styles and positions of the legend
data() {
return {
legendData: {
orient: 'vertical',
left: '40%',
top: 'center',
icon: 'circle', // 图例色块是方还是圆
itemGap: 20,
itemWidth: 8,
padding: 0,
selectedMode: false,
triggerEvent: true,
textStyle: {
// 字符串模板
rich: {
a: {
align: 'left',
color: '#19273B',
width: 130,
padding: [0, 8, 0, 0]
},
b: {
align: 'left',
color: '#8D97A4',
width: 55,
padding: [0, 8, 0, 0]
},
c: {
align: 'left',
color: '#19273B'
}
}
}
}
}
}
The code of the specific picture
//环形图
initCircularChart() {
var echarts = require('echarts') // 初始化
var circularChart = document.getElementById('circularChart') // 对应地使用ByClassName
// 处理图例中的数据
const _that = this
_that.legendData.formatter = function(name) {
// _that.reasonInfoList 环形图的数据
let str = ''
let rate
let value
for (let i = 0; i < _that.reasonInfoList.length; i++) {
if (_that.reasonInfoList[i].name === name) {
rate = toThousandFilter(_that.reasonInfoList[i].rate * 100) // 这里我处理了一下百分数
value = _that.reasonInfoList[i].value
str = `{a|${
name}} {b|${
rate}%} {c|${
value}}`
return str // 因为只能返回一个值 所以将一行数据拼成一个字符串
}
}
}
var myChart = echarts.init(circularCharts, walden)// walden: 主题
myChart.setOption({
title: {
text: '失败原因', // 图的名字
left: 'left',
triggerEvent: true
},
legend: this.legendData, // 图例直接引用
series: [{
type: 'pie',
radius: [45, 65],
center: ['20%', '50%'],
hoverAnimation: false, // true 鼠标移入会放大
label: {
// 环形图中间部分显示所有的总数
show: true,
position: 'center',
fontSize: '12',
formatter: `{a|${
failedOrderNum}}` + '\n' + `{b|${
'订单总数'}}`,
rich: {
a: {
color: '#19273B'
},
b: {
color: '#8D97A4'
}
}
},
data: this.reasonInfoList, // 所有数据的数组
stillShowZeroSum: true // 是否在数据和为0(一般情况下所有数据为0) 的时候仍显示扇区
}]
})
}