项目需要自定义legend,仅用echarts自身配置无法实现,使用div绘制legend,再使用echarts api实现legend点击置灰效果
<div
class="item"
v-for="(item, index) in data"
key="index"
@click="dispatchEvent(item, index)">
<div
class="circle"
tyle="{ backgroundColor: getColor(item) }">
</div>
<p>{
{ item.name }}</p>
<div class="num">{
{ item.cent }}</div>
</div>
</div>
getColor用于获取数据对应的颜色块,如果禁用显示灰色
color是项目中定义的一个长度为13的颜色数组
computed: {
getColor() {
return (obj) => {
if (obj.disable) {
return '#E0E0E0';
}
const index = this.data.findIndex((item) => item.name === obj.name);
if (this.color[index]) {
return this.color[index];
} else {
return this.color[index % 13];
}
};
},
},
调用echarts api,根据名称切换legend
dispatchEvent(item, index, key) {
item.disable = !item.disable;
this.$set(this.data, index, item);
this.$refs.chart.dispatchAction({
type: 'legendToggleSelect',
name: item.name,
});
},
需要注意:
option中legend属性必须要写,不然不能正常触发legendToggleSelect
legend: {
show: false,
}