基本原理: 1、创建一个用于展示图形的vue组件,保留接收数据的接口,作为子组件使用。 2、在父组件中引用上述子组件,同时传递数据给子组件。 本文在main.js中全局引入echarts,代码为:
import * as echarts from 'echarts';
Vue.prototype.$echarts = echarts
子组件echartscom.vue:
<template>
<div class="echartsCommon">
<div style="width: 80rem; height: 20rem" class="echarts" ref="piechart"></div>
</div>
</template>
export default {
name: 'echartscom',
mounted() {
this.drawCharts();
},
props: ['chartData'],
methods: {
drawCharts() {
let myChart = null;
myChart = this.$echarts.init(this.$refs.piechart);
myChart.setOption({
tooltip: {
trigger: 'item'
},
color: ['rgb(238,102,102)', 'rgb(145,202,117)', 'rgb(115,202,222)'],
series: [{
type: 'pie',
radius: '75%',
data: this.chartData,
itemStyle: {
normal: {
label: {
show: true,
formatter: '{b} : {d}%',
fontSize:16
}
}
}
}]
})
window.addEventListener('resize', function() {
myChart.resize();
});
},
}
}
父组件: 这里用v-for实现多次调用子组件
<div>
<b-card v-for="(item,index) in dataset" :key="index" class="mt-2" :sub-title="(index+1)+'、'+item[0]['question']">
<b-card-text>
<echartscom :chartData="item" v-if="showFig"></echartscom>
</b-card-text>
</b-card>
</div>
import echartscom from '@/components/echartscom.vue'
export default {
data() {
return {
dataset: [],
showFig: true,
}
},
components: {
echartscom,
},
methods: {
getSta: function() {
this.$axios.post("disciplineCollect.php", {
act: 'sta',
cpcname: this.cpcname
}).then(rs => {
if (rs.data.data[0]['answer'].length > 0) {
this.showFig = true;
for (let each of rs.data.data) {
this.dataset.push(each.answer);
}
} else {
this.showFig = false;
this.dataset = [];
this.dismissCountDown = this.dismissSecs;
this.alertType = "danger"
this.alertMsg = "暂无数据。"
}
})
}
}
}
需要注意的是,根据echarts饼状图的数据结构要求,后端从数据库中读取出来的数据需要格式化为形如 name、value这样的结构,sql语句中往往需要group by。
|