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; // 如果没有找到
},
相关推荐
m0_6948455722 分钟前
Oh My Zsh 使用指南:Zsh 终端配置与插件管理教程
服务器·前端·小程序·开源·github
英俊潇洒美少年25 分钟前
React19 useActionState的注意事项
前端·javascript·react.js
huaqianzkh27 分钟前
两个 ASP.NET Core Web API 模板核心区别
前端·后端·asp.net
发现一只大呆瓜30 分钟前
性能优化:CDN 缓存加速与调度原理
前端·javascript·面试
chaofan98035 分钟前
2026 轻量模型三国杀:Flash-Lite vs GPT-4.1 Nano vs Haiku,技术选型到底该站谁?
前端·人工智能·microsoft
小蜜蜂dry35 分钟前
nestjs学习 - 守卫
前端·nestjs
Lsx-codeShare1 小时前
前端发版后页面白屏?一套解决用户停留旧页面问题的完整方案
前端·javascript·前端框架·vue·vite
心柠1 小时前
TypeScript的知识梳理
前端·javascript·typescript
Cache技术分享1 小时前
354. Java IO API - 获取路径信息
前端·后端
北寻北爱1 小时前
面试篇-vue中第三方库的使用(echarts)
前端