由于新型冠状病毒疫情感染,我司要出一套AI智能体温检测供社区,公司或者工厂使用。那么管理平台便于查看统计数据的话,最好就有图形结合便于领导查看。所以,这篇文章就带领大家用vue制作echarts饼图(pie)。
先上效果图:
一、安装echarts
首先要安装项目依赖 :
npm install echarts --save-dev
二、HTML部分
这里想说一下ref属性在这里的意思。ref 的作用是给DOM元素或子组件注册引用信息。引用信息会根据父组件的 $refs 对象进行注册。如果在普通的DOM元素上使用,引用信息就是元素; 如果用在子组件上,引用信息就是组件实例。
所以,如果想在Vue中直接操作DOM元素,就必须用ref属性进行注册。
<div class="title">检测占比图</div>
<div class="body">
<div ref="checkStatChart"></div>
</div>
三、引入依赖
在想要输出饼图的vue文档中引入依赖。如果你的饼图在多处使用,那么你可以在main.js中全局引入。
import echarts from 'echarts'
四、新建js文件编写方法
使用另外的js文件编写js方法可以单独的管理图表。也有利于文档的资源管理。在这里我的js文档以chartOption
为例。
//饼状图
export const statCountPieOption = function ({
total_count, //总人流量
overtemp_count, //超温数量
masklack_count, //未戴口罩数量
overtempAndMasklack_count, //超温且未戴口罩数量
}) {
//正常
let normal_count = total_count - overtemp_count
- masklack_count - overtempAndMasklack_count;
//有戴口罩
let maskHave_count = total_count - masklack_count
- overtempAndMasklack_count;
//正常温度
let normalTemp_count = total_count - overtemp_count
- overtempAndMasklack_count;
function serieOption (i, nameList) {
let startX = (2*i-1)*100/6 + '%';
return {
type: 'pie',
radius: '70%',
center: [ startX, '50%' ],
label: {
position: 'outside',
fontSize: 10,
color: '#333',
lineHeight: 13,
width: '100%',
align: 'center',
alignTo: 'none',
formatter ({ name, percent }) {
let isAlarm = name != '正常' && name != '正常温度'
&& name != '有戴口罩';
return `${name}${ isAlarm ? '预警':'' }\n${percent}%`;
}
},
labelLine: {
show: false,
length: 5,
length2: 5
},
itemStyle: {
color ({ data }) {
return {
'超温': '#E50000',
'未戴口罩': '#E3D845',
'超温且未戴口罩': '#F08638',
'正常': '#29AD65',
'正常温度': '#29AD65',
'有戴口罩': '#29AD65'
}[data.name];
}
},
data: nameList.map((name) => {
return {
name,
value: {
'超温': overtemp_count,
'未戴口罩': masklack_count,
'超温且未戴口罩': overtempAndMasklack_count,
'正常': normal_count,
'有戴口罩': maskHave_count,
'正常温度': normalTemp_count
}[name] || 0,
label: {
position: ['正常', '有戴口罩', '正常温度'].includes(name) ? 'inside':null
}
}
})
};
};
return {
series: [
serieOption(1, [ '超温', '未戴口罩', '超温且未戴口罩', '正常' ]),
serieOption(2, [ '超温', '正常温度' ]),
serieOption(3, [ '未戴口罩', '有戴口罩' ])
]
};
};
五、引入js文件
引入chartOption
文件中的方法。
import {
statCountPieOption
} from './chartOption'
然后根据后端传过来的数据更新图表。
getStatCount() {
this.$commonReq(
"/xxxx/count", // 接口API
this.getSearc(), // 查询条件返回的数据
({
total_count, //总人流量
overtemp_count, //超温数量
masklack_count, //未戴口罩数量
overtempAndMasklack_count //超温且未戴口罩数量
}) => {
let normal_count =
total_count -
overtemp_count -
masklack_count -
overtempAndMasklack_count;
this.statData = {
total_count,
overtemp_count,
masklack_count,
overtempAndMasklack_count,
normal_count
};
//更新图表
this.statPieChart =
this.statPieChart || echarts.init(this.$refs.statPieChart);
this.statPieChart.setOption(statCountPieOption(this.statData));
}
);
},