ECharts饼图下钻

背景

项目上需要对Echarts饼图进行功能定制,实现点击颜色块,下钻显示下一层级占比

说明

饼图实现点击下钻/面包屑返回的功能

实现

  • 数据结构
js 复制代码
[
  {
    name: 'a',
    value: 1,
    children: [...]
  },
  ...
]
  • 点击下钻
js 复制代码
// 为图表绑定点击事件(需要在destroy前进行事件解绑)
this.myChart.on('click', (e) => {
  if (e.data?.children) {
    this.source = e.data.children // 将子级用于当前图表显示
    this.breadcrumbList.push(e.data.name) // 面包屑添加子级名称
  }
})
  • 面包屑返回
html 复制代码
<!-- 面包屑-显示下钻层级及点击返回 数据结构: [xxx, xxx, ...] -->
<row class="breadcrumb" v-if="drillAble">
  <span
    class="clickable flex"
    v-for="(item, index) in breadcrumbList"
    :key="index"
    @click="handleCrumbClick(index)"
  >
    <OverflowTip style="max-width: 200px" :content="item">
      {{ item }}
    </OverflowTip>
    <span class="px-5" v-if="index < breadcrumbList.length - 1"> / </span>
  </span>
</row>
js 复制代码
handleCrumbClick(index) { // index为点击面包屑的层级
  if (index === this.breadcrumbList.length - 1) return // 点击当前层级 不做任何操作
  this.breadcrumbList.splice(index + 1) // 删除下级面包屑
  if (index === 0) {
    this.source = this.originData // 根级别 直接赋值
  } else {
    const parentName = this.breadcrumbList[index]
    const parentData = this.findParentData(this.originData, parentName) // 递归查找
    this.source = parentData?.children || []
  }
},
findParentData(data, name) {
  for (const item of data) {
    if (item.name === name) {
      return item; // 找到对应的父级节点
    }
    if (item.children) {
      const result = this.findParentData(item.children, name);
      if (result) {
        return result; // 在子级中递归查找
      }
    }
  }
  return null; // 如果没有找到
},
相关推荐
TAEHENGV3 小时前
导入导出模块 Cordova 与 OpenHarmony 混合开发实战
android·javascript·数据库
小徐_23333 小时前
不如摸鱼去的 2025 年终总结,今年的关键词是直面天命
前端·年终总结
GISer_Jing3 小时前
交互式圣诞树粒子效果:手势控制+图片上传
前端·javascript
3824278273 小时前
CSS 选择器(CSS Selectors) 的完整规则汇总
前端·css
放逐者-保持本心,方可放逐3 小时前
PDFObject 在 Vue 项目中的应用实例详解
前端·javascript·vue.js
龙仔CLL4 小时前
vue2项目使用zoom解决pc端浏览器百分比缩放,布局样式不兼容问题
vue.js·html·zoom
一 乐4 小时前
养老院信息|基于springboot + vue养老院信息管理系统(源码+数据库+文档)
java·数据库·vue.js·spring boot·后端
捻tua馔...4 小时前
mobx相关使用及源码实现
开发语言·前端·javascript
cypking4 小时前
解决 TypeScript 找不到静态资源模块及类型声明问题
前端·javascript·typescript
想学后端的前端工程师4 小时前
【Webpack构建优化实战指南:从慢到快的蜕变】
前端