(1)在项目中安装Echarts
npm install echarts --save
(2)在页面中引入Echarts
import * as echarts from 'echarts';
(3)定义ECharts的option(以基础柱状图为例)
//基础柱状图
export const barOption = {
tooltip: {
trigger: 'axis',
axisPointer: {
type: 'shadow',
},
},
title: {
text: '',
left: '',
},
grid: {
left: '3%',
right: '4%',
bottom: '3%',
containLabel: true,
},
xAxis: [
{
type: 'category',
data: [] as any,
axisTick: {
alignWithLabel: true,
},
},
],
yAxis: [
{
type: 'value',
// axisLabel: {
// formatter: function (value: number) {
// // 使用千分位分隔符格式化数字
// return value.toLocaleString();
// },
// },
},
],
series: [
{
name: '',
type: 'bar',
barWidth: '60%',
data: [] as any,
label: {
show: true, // 显示标签
position: 'top', // 标签位置,可选值:'top', 'right', 'bottom', 'left', 'inside', 'insideLeft', 'insideRight', 'insideTop', 'insideBottom', 'insideTopLeft', 'insideTopRight', 'insideBottomLeft', 'insideBottomRight'
formatter: function (params: any) {
// 使用千分位分隔符格式化数字
return params.value.toLocaleString();
},
},
},
],
};
(4)(必须)定义父容器的高度和宽度
<div id="bar"></div>
/* 必须设置父容器的宽度和高度,否则图表无法显示 */
#bar{
width: 100%;
height: 400px;
}
(5)获取数据,渲染ECharts图表
const yData = ref<any[]>([]);
const handleRowNum = async () => {
await useWelApi()
.queryRowNum()
.then((res: any) => {
const data = res.data.data;
xData.value.forEach((item: any) => {
const exist = data.find((ele: any) => item === ele.date.split(' ')[0]);
if (exist !== undefined) {
yData.value.push(exist.num);
} else {
yData.value.push(0);
}
});
});
const rowNumDom = document.getElementById('rowNumId');
const rowNumBarChart = echarts.init(rowNumDom);
barOption.title.text = '最近7天同步行数统计';
barOption.title.left = '';
barOption.xAxis[0].data = xData.value;
barOption.series[0].name = '同步行数';
barOption.series[0].data = yData.value;
rowNumBarChart && rowNumBarChart.setOption(barOption);
};
//加载页面时执行
onMounted(() => {
handleRowNum();
});
到此结束!