<template>
<div
ref="chart"
style="width: 100%;height: 100%"
></div>
</template>
<script>
import * as echarts from 'echarts'
export default {
name: 'EchartPie1',
props: {
yData: {
type: Array,
default: () => [100, 25, 15, 78]
},
areaColor: {
type: Array,
default: () => ['#F1B267', '#479FFE', '#69EAFE', '#90FFAD']
},
legend: {
type: Array,
default: () => ['煤矿企业', '化工企业', '政府企业单位', '食品企业']
},
unit: {
type: String,
default: ''
}
},
data () {
return {
chart: null,
option: null,
index: 0,
obj: {
num: '',
title: ''
}
}
},
watch: {
index: {
handler (i) {
if (i < this.yData.length) {
this.$nextTick(() => {
this.initChart(this.chart, this.yData)
})
} else {
this.index = 0
}
},
immediate: true
}
},
computed: {
getPercent () {
let total = 0
this.yData.forEach((item) => {
total += item
})
return total
}
},
mounted () {
this.chart = echarts.init(this.$refs.chart)
window.addEventListener('resize', this.handleResizeCharts)
},
beforeDestroy () {
window.removeEventListener('resize', this.handleResizeCharts)
this.chart.dispose()
},
methods: {
handleResizeCharts () {
this.chart.resize()
},
initChart (chart, yData) {
const color = this.areaColor
this.option = {
title: [
{
text: `${this.formatterTitle(this.obj.title)}`,
x: 'center',
top: 'center',
textStyle: {
color: '#666',
fontFamily: 'Microsoft YaHei',
fontWeight: 400,
fontSize: 12
}
}
],
grid: {
left: 0,
top: 0,
right: 0,
bottom: 0,
containLabel: true
},
tooltip: {
show: false
},
series: [
{
name: '',
type: 'pie',
radius: ['73%', '86%'],
center: ['50%', '50%'],
data: yData,
animationEasing: 'elasticOut',
emphasis: {
disable: false,
scale: true,
scaleSize: 5
},
itemStyle: {
normal: {
color: function (colors) {
return color[colors.dataIndex]
}
}
},
labelLine: { show: false },
label: { show: false }
}
]
}
chart.setOption(this.option)
this.changeAuto(chart)
},
changeAuto (chart) {
const that = this
setTimeout(function () {
if (that.index < that.yData.length) {
chart.dispatchAction({ type: 'downplay', seriesIndex: 0 })
chart.dispatchAction({
type: 'highlight',
seriesIndex: 0,
dataIndex: that.index
})
that.$set(that.obj, 'title', that.legend[that.index])
that.$set(that.obj, 'num', that.yData[that.index])
that.index++
} else {
that.index = 0
}
}, 2000)
},
formatterTitle (params) {
let newParamsName = ''
const paramsNameNumber = params.length
const provideNumber = 4
const rowNumber = Math.ceil(paramsNameNumber / provideNumber)
if (paramsNameNumber > provideNumber) {
for (let p = 0; p < rowNumber; p++) {
let tempStr = ''
const start = p * provideNumber
const end = start + provideNumber
if (p === rowNumber - 1) {
tempStr = params.substring(start, paramsNameNumber)
} else {
tempStr = params.substring(start, end) + '\n'
}
newParamsName += tempStr
}
} else {
newParamsName = params
}
return newParamsName
}
}
}
</script>