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; // 如果没有找到
},
相关推荐
文艺理科生7 分钟前
Nuxt.js入门指南-Vue生态下的高效渲染技术
前端·vue.js·nuxt.js
夏小花花11 分钟前
vue3 ref和reactive的区别和使用场景
前端·javascript·vue.js·typescript
outsider_友人A13 分钟前
前端也想写后端(3)中间件Middleware、管道Pipes、拦截器Interceptors
前端·node.js·nestjs
静Yu14 分钟前
Webpack 你到底在干什么!?
前端
掘金安东尼15 分钟前
前端周刊第427期(2025年8月4日–8月10日)
前端·javascript·面试
阿华的代码王国15 分钟前
【Android】适配器与外部事件的交互
android·xml·java·前端·后端·交互
mit6.82418 分钟前
[AI React Web] 包与依赖管理 | `axios`库 | `framer-motion`库
前端·人工智能·react.js
老虎062722 分钟前
JavaWeb前端(HTML,CSS具体案例)
前端·css·html
Mintopia28 分钟前
一个月速成 AI 工程师:从代码小白到智能工匠的修炼手册
前端·javascript·aigc
Mintopia31 分钟前
Next.js 全栈:接收和处理请求
前端·javascript·next.js