子组件
<!-- 自定义 echart 组件 -->
<template>
<div>
<!-- echart表格 -->
<div :id="myChartId" :style="echartStyle"></div>
</div>
</template>
<script>
import echarts from 'echarts';
export default {
props: {
// ID
myChartId: {
type: String,
default:'myChartId',
},
// 样式
echartStyle: {
type: String,
default:''
},
// 标题文本
titleText: {
type: String,
default: ''
},
// 提示框键名
tooltipFormatter: {
type: String,
default: ''
},
// 扇形区域名称
opinion: {
type: Array,
default(){
return []
}
},
// 提示框标题
seriesName: {
type: String,
default: ''
},
// 扇形区域数据
opinionData: {
type: Array,
default(){
return []
}
},
},
data(){
return {
//
}
},
watch: {
opinionData(val,oldval){
this.$nextTick(function() {
this.drawPie(this.myChartId)
})
}
},
methods: {
// 监听扇形图点击
eConsole(param) {
// 向父组件传值
this.$emit("echarEvent",param);
},
// 绘制饼状图
drawPie(id){
this.charts = echarts.init(document.getElementById(id));
this.charts.on("click", this.eConsole);
console.log(this.opinion,this.opinionData)
this.charts.setOption({
title: {
text: this.titleText, // 标题文本
left: 'center'
},
tooltip : {},
legend: {
bottom: 20,
left: 'center',
data: this.opinion // 底部标签名称
},
series : [
{
name:this.seriesName, // 提示框标题
type: 'pie',
radius : '65%',
center: ['50%', '30%'],
data:this.opinionData, // 扇形区域数据
itemStyle: {
emphasis: {
shadowBlur: 10,
shadowOffsetX: 0,
shadowColor: 'rgba(0, 0, 0, 0.5)'
},
}
}
],
color:[ '#aa5b71','#fd7d36','#f1ccb8','#f1b8e4','#ff9b6a','#b7d28d','#d9b8f1', ' #b8f1cc', '#b8f1ed', '#f1f1b8']
})
}
}
}
</script>
父组件引用示例
<style lang="less">
@import "./home.less";
@import "../../styles/common.less";
</style>
<template>
<Row>
<Col span="8">
<draw-pie
:myChartId="'mychart1'"
:echartStyle="'width:300px;height:500px;'"
:titleText="drawPieInfo.titleText"
:opinionData="drawPieInfo.opinionData"
@echarEvent="echarEvent"
></draw-pie>
</Col>
<Col span="4">
</Col>
</Row>
</template>
<script>
import drawPie from '@/components/zhEchart/drawPie.vue'
import {
countLawCase
} from '@/api/homeDate';
export default {
name: 'home',
components: {
drawPie
},
data () {
return {
drawPieInfo: {
titleText: "案件状态",
subText: "总计",
opinionData: {} //扇形数据
},
lawCaseCount:[],//案件状态
};
},
mounted () {
this.initChart();
},
methods: {
initChart(){//初始化chart数据
countLawCase().then(res=>{
if(res.data.state==100){
let data=res.data.data;
this.lawCaseCount=data.lawCaseCount;
var that=this;
var ary=Object.keys(this.lawCaseCount).map(function (key) {
return {
name: key,
value: that.lawCaseCount[key]//获取扇形数据
}
});
this.drawPieInfo.opinionData=ary;//设置扇形数据
this.drawPieInfo.subText = "总计:" + this.getTotol(this.lawCaseCount); //设置总数
}else{
this.$Message.error(res.data.message);
}
});
},
echarEvent(){
},
getTotol(ary) {
//统计总数
var totol = Object.keys(ary).reduce(function(all, key) {
return all + ary[key];
}, 0);
return totol;
},
},
};
</script>
值得注意的是:由于echart数据依赖DOM更新,再次赋值时需要重新初始化echart,在父组件异步获取数据传入子组件时,要用watch监听传入的值并重新进行DOM渲染,数据更新了但视图并没有及时更新因此就需要$nextTick进行DOM监听来重新初始化echart