目的
- 减少重复代码量
- 统一风格
- 全局事件处理方便维护
- 可以根据实际需求暴露对应的事件和方法
### 代码
<template>
<div ref="chart" class="my-chart"></div>
</template>
<script>
import * as echarts from 'echarts'
export default {
name: 'EChart',
props: {
option: {
type: Object,
default: () => {
return null
}
}
},
data() {
return {
myChart: null
}
},
watch: {
option(newValue) {
if (newValue) {
this.loadChart()
}
}
},
mounted() {
this.myChart = echarts.init(this.$refs.chart)
if (this.option) {
this.loadChart()
} else {
this.myChart.showLoading({
text: '数据加载中...',
color: '#81B5FD',
textColor: '#81B5FD',
maskColor: 'rgba(255, 255, 255, 0.2)',
showSpinner: false,
zlevel: 0
})
}
},
methods: {
loadChart() {
this.myChart.hideLoading()
this.myChart.setOption(this.option)
window.addEventListener('resize', () => {
this.myChart.resize()
})
}
}
}
</script>
<style lang="less" scoped>
.my-chart {
width: 100%;
height: 100%;
}
</style>
使用
<template>
<my-card title="业务类别">
<e-chart :option="option" />
</my-card>
</template>
<script>
export default {
name: 'BusinessCategory',
data() {
return {
option: null,
seriesData: [
{ value: 1048, name: '房建' },
{ value: 735, name: '铁路' },
{ value: 580, name: '公路' },
{ value: 484, name: '贸易' },
{ value: 300, name: '境外开矿' }
]
}
},
mounted() {
this.handleChartInit()
},
methods: {
handleChartInit() {
this.option = {
tooltip: {
trigger: 'item',
formatter: '{b} </br>{c}({d}%)'
},
label: {
alignTo: 'edge',
formatter: '{name|{b}}\n{time|{c}} ({time|{d}}%)',
minMargin: 5,
edgeDistance: 10,
lineHeight: 15,
rich: {
time: {
fontSize: 10,
color: '#999'
}
}
},
series: [
{
name: 'Access From',
type: 'pie',
radius: ['45%', '70%'],
data: this.seriesData,
emphasis: {
itemStyle: {
shadowBlur: 10,
shadowOffsetX: 0,
shadowColor: 'rgba(0, 0, 0, 0.5)'
}
}
}
]
}
}
}
}
</script>