echarts 柱状图选中单个柱形时其颜色变化
在我们使用echarts柱形图时可能需要用到点击柱形使当前点击柱形高亮显示。
echarts中有自带的属性可以对点中柱进行颜色的变换
series: [
{
type: 'bar',
itemStyle: {
borderRadius: [3, 3, 0, 0], // 柱体宽度
color: 'skyblue' // 未选中柱颜色
}
emphasis: {
itemStyle: {
color: '#007DFF' // 选中柱颜色
}
}
}
]
// 不使用 echarts 中自带属性实现
1.先在data中保存柱形图被点击柱的 index 。
data () {
return {
echartsIndex: 0
};
},
2.基准线是随着点击柱的变化而移动的,因此我们只需要获取到基准线的位置,这个位置也就是被点击的柱形的位置,将基准线的 index 赋值给 echartsIndex。
tooltip: {
formatter: (value, index) => {
this.echartsClick(value[0]); // 获取到基准线所处位置的信息
},
}
echartsClick (params) {
this.echartsIndex = params.dataIndex // 将基准线的位置赋值给 echartsIndex
}
series: [
{
type: 'bar',
itemStyle: {
borderRadius: [3, 3, 0, 0],
color(params) {
if(params.dataIndex == ind) {
colorList[params.dataIndex] = '#007DFF'
}else {
colorList[params.dataIndex] = '#95D9F4'
}
return colorList[params.dataIndex]
}
}
}
]
3.对 echartsIndex 进行赋值
this.echarts.dispatchAction({
type: 'showTip',
seriesIndex: 0,
dataIndex: this.echartsIndex
});
4.若无法动态使echarts图表点击柱动态改变颜色,需要重新渲染echarts,那么就进行事件监听
watch: {
echartsIndex() {
this.$nextTick(() => {
this.chartInit();
});
},
}