需求:
- 横向柱状图,数据放在条形上展示。
- 悬浮有特定样式展示。
- 点击柱子和label能拿到对应数据进行处理
横向柱状图数据在条形图上显示实现方式
使用ECharts的yAxis.axisLabel
配置项将数据标签显示在条形图上。通过设置inside: true
将标签嵌入坐标轴区域,调整verticalAlign
和align
控制对齐方式,结合padding
微调位置。示例代码片段:
axisLabel: {
show: true,
inside: true,
fontSize: 12,
verticalAlign: 'bottom',
align: 'left',
padding: [20, 0, 10, 0]
}
通过formatter
函数自定义tooltip内容,实现悬停时显示完整数据:
formatter: function(params) {
return `${params[0].name} : ${params[0].value}`;
}
柱状图/坐标轴点击事件处理
在yAxis配置中启用triggerEvent: true
允许坐标轴触发事件,配合ECharts实例的on
方法监听点击事件:
yAxis: {
triggerEvent: true
}
// 在图表初始化后
chartInstance.on('click', 'yAxis.category', function(params) {
console.log('点击的类别:', params.value);
});
对于柱状图本身的点击,直接监听series的点击事件:
chartInstance.on('click', 'series.bar', function(params) {
console.log('柱状图数据:', params.data);
});
Hover样式定制
- 因为需要考虑无数据情况和多种条件切换,所以监听数据变化拿到实例后再调用方法
- 此处的label实际是y轴的效果,所以添加鼠标事件实现样式。
<ContentWrap title="xxxx" style="min-height: 320px;height: calc(-138px + 50vh); " class="mb0px">
<aq-empty v-if="isEmpty.view1" :image-size="'10%'" />
<EChart v-else ref="attachIpChartRef" :options="vBar1options" width="100%" height="100%" />
</ContentWrap>
-------------------------------------------
watch(
() => isEmpty.value.view1,
(newVal) => {
if (!newVal) {
nextTick(() => {
const chartInstance = attachIpChartRef.value?.getEchartsInstance?.();
if (chartInstance) {
chartInstance.off('click');
chartInstance.off('mouseover');
chartInstance.off('mouseout');
chartInstance.on('click', (params) => {
if (params.componentType === 'series' || params.componentType === 'yAxis') {
const label = params.name || params.value;
const ip = label.split('(')[0];
router.push({
path: '/protect-log',
query: {
fromType: '2',
srcIp: ip,
timeType: activeType.value,
},
});
}
});
chartInstance.on('mouseover', (params) => {
if (params.componentType === 'yAxis') {
const el = params.event?.target;
if (el && el.style) {
el.style.backgroundColor = 'rgb(231.2, 238.8, 251.4)';
el.style.fill = '#409EFF';
el.style.cursor = 'pointer';
el.style.fontWeight = 'bold';
}
}
});
// 移出标签时还原样式
chartInstance.on('mouseout', (params) => {
if (params.componentType === 'yAxis') {
const el = params.event?.target;
if (el && el.style) {
el.style.fill = '#333'; // 原始颜色
el.style.cursor = 'default';
el.style.fontWeight = 'normal';
}
}
});
}
});
}
},
{ immediate: true }
);