调用方式类似与柱图和线图的组件柱图/线图组件
和柱图线图组件一样,是以前云桌面项目写的,功能不多,还可以优化或者拓展很多,后面用vue3开发某个项目的时候有基于这个做过完善和拓展,不过就不是v2的组件了
- html和css部分
<template>
<div ref="myPieChart"
class="com-pie-chart" />
</template>
<style scoped>
.com-pie-chart {
width: 100%;
height: 100%;
}
</style>
- js部分
<script>
export default {
name: 'PieChart',
props: {
colors: {
type: Array,
default: () => ['#fac859', '#079ee7'],
},
// 数据,数据结构就为数组对象结构[{key1:'', key2:'', key3:'',...},{}]
sourceData: {
type: Array,
default: () => [],
},
// echarts配置[{field: '', name: '', color: '', type: 'line',...}, {}]
// 多个对象代表多个线或柱
// field(字段名),name(series的名字),color(颜色,可单个,可数组两值渐变),type(图类型)
seiresConfig: {
type: Array,
default: () => [],
},
// legend配置
legendConfig: {
type: Object,
default: () => { },
},
tooltipFormatter: {
type: String,
default: '{b}:{c}人',
},
isTooltip: {
type: Boolean,
default: true,
},
// 标题
title: {
type: Object,
default: () => { },
}
},
data () {
return {}
},
watch: {
sourceData: {
handler () {
this.drawChart()
},
deep: true,
},
},
mounted () {
this.drawChart()
},
methods: {
// 画图
drawChart () {
const chart = echarts.init(this.$refs.myPieChart, null, { renderer: 'canvas' })
const legends = []
const seriesList = this.seiresConfig.map((item, index) => {
legends.push(item.name)
const datas = this.sourceData.map(sou => {
return {
name: sou.name,
label: sou.label || {},
value: sou[item.field]
}
})
const obj = {
type: 'pie',
name: item.name || '',
data: datas,
radius: item.radius || '50%',
center: item.center || ['50%', '50%'],
avoidLabelOverlap: true, // 避免重叠
labelLine: {
show: true,
normal: {
lineStyle: {
width: 1,
},
length: 25,
length2: 40,
},
...item.labelLine
},
label: {
color: '#fff',
show: true,
formatter: '{name|{b}} \n\n{per|{c}人}',
padding: [0, -50, 0, -50],
rich: {
number: {
fontSize: 12,
color: 'inherit',
},
name: {
fontSize: 12,
color: '#fff',
},
per: {
color: 'inherit',
fontSize: 12,
padding: [2, 4],
borderRadius: 2,
},
},
...item.label
},
}
return obj
})
const option = {
title: {
show: false,
left: 'center',
top: 'top',
...this.title
},
tooltip: {
show: this.isTooltip,
trigger: 'item',
confine: true,
formatter: this.tooltipFormatter
},
color: this.colors,
legends: {
data: legends,
top: 20,
right: 20,
orient: 'horizontal',
textStyle: {
color: '#fff',
fontSize: 12,
},
...this.legendConfig,
},
series: seriesList,
}
chart.setOption(option)
chart.on('click', item => {
this.$emit('barClick', item)
})
},
},
}
</script>