
封装组件pie-bar.vue
<template>
<div :class="className" :style="{ height: height, width: width }" />
</template>
<script>
import * as echarts from 'echarts';
import resize from "./mixins/resize"; // 动态自适应
require('echarts/theme/macarons')
var option;
export default {
mixins: [resize],
name: 'PieBar',
components: {},
props: {
className: {
type: String,
default: 'chart'
},
width: {
type: String,
default: '80vw'
},
height: {
type: String,
default: '500px'
},
pieBarData: {
type: Object,
required: true,
default: function () {
return {
}
}
}
},
data () {
return {
chart: null
}
},
mounted () {
this.$nextTick(() => {
this.initChart()
})
},
beforeDestroy () {
if (!this.chart) {
return
}
this.chart.dispose()
this.chart = null
},
watch: {
pieBarData: {
deep: true,
handler (val) {
// this.$nextTick(() => {
this.setOptions(val)
// });
}
}
},
methods: {
initChart () {
var that = this
this.chart = echarts.init(this.$el, 'macarons')
this.setOptions(that.pieBarData)
//更新
this.chart.on('updateAxisPointer', event => {
let xAxisInfo = event.axesInfo[0];
if (xAxisInfo) {
let dimension = xAxisInfo.value + 1;
this.chart.setOption({
series: {
id: 'pie',
label: {
formatter: '{b}: {@[' + dimension + ']} ({d}%)'
},
encode: {
value: dimension,
tooltip: dimension
}
}
});
}
});
this.chart.on('click', event => {
if (event.seriesType == 'pie') {
console.log(event.data[0])
this.$emit('func', event.data[0])
}
})
},
setOptions (newVisitis) {
this.chart.setOption({
legend: {},
title: {
text: '',
// left: 'center',
},
tooltip: {
trigger: 'axis',
showContent: true,
backgroundColor: '#F6F8FC',
},
dataset: {
source: newVisitis.source
},
xAxis: {
type: 'category',
min: 0,
max: newVisitis.source[0].length + 1
},
yAxis: {
gridIndex: 0
},
grid: {
// top: '55%'
left: '3%'
},
series: [
{
type: 'bar', barWidth: 25, seriesLayoutBy: 'row',
emphasis: { focus: 'series' }
},
{
type: 'bar', barWidth: 25, seriesLayoutBy: 'row',
emphasis: { focus: 'series' }
},
{
type: 'bar', barWidth: 25, seriesLayoutBy: 'row',
emphasis: { focus: 'series' }
},
{
type: 'bar', barWidth: 25, seriesLayoutBy: 'row',
emphasis: { focus: 'series' }
},
{
type: 'pie',
id: 'pie',
radius: '30%',
center: ['65%', '35%'],
label: {
formatter: '{b}: {@2012} ({d}%)'
},
encode: {
itemName: newVisitis.source[0],
value: newVisitis.source[1],
tooltip: newVisitis.source[1]
}
}
]
})
},
},
}
</script>
父组件引用
<PieBar
:pieBarData="pieBarData"
width="100vw"
></PieBar>
import PieBar from '@/components/XXX/pie-bar'
export default {
components: { PieBar },// 注册组件
data() {
return {
pieBarData: { source: [] },
}
},
}
数据结构
pieBarData: {
source: [
['product', '2012', '2013', '2014', '2015', '2016', '2017'],
['Milk Tea', 56.5, 82.1, 88.7, 70.1, 53.4, 85.1],
['Matcha Latte', 51.1, 51.4, 55.1, 53.3, 73.8, 68.7],
['Cheese Cocoa', 40.1, 62.2, 69.5, 36.4, 45.2, 32.5],
['Walnut Brownie', 25.2, 37.1, 41.2, 18, 33.9, 49.1]
]
},
网友评论