vue element ui 简单表格下钻逻辑浅记

在 Vue.js 中结合 Element UI 来实现点击表格字段跳转到对应字段的表格,并使用面包屑导航以方便用户随时跳回之前的层级,可以通过以下步骤来完成:

步骤 1: 准备数据结构

首先,你需要一个嵌套的数据结构来表示不同级别的表格数据。例如:

const data = [
  {
    id: 1,
    name: 'Parent 1',
    children: [
      {
        id: 11,
        name: 'Child 1',
        children: [
          { id: 111, name: 'Grandchild 1', children: [] },
          { id: 112, name: 'Grandchild 2', children: [] }
        ]
      },
      {
        id: 12,
        name: 'Child 2',
        children: []
      }
    ]
  },
  // 更多层级...
];

步骤 2: 创建 Vue 组件(直接复制此组件即可)

创建一个 Vue 组件,它包含一个 el-table 和一个 el-breadcrumb 组件。el-table 将用于显示数据,而 el-breadcrumb 将用于导航。

<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item v-for="(crumb, index) in breadcrumbs" :key="index" @click="jumpTo(index)">
        {{ crumb }}
      </el-breadcrumb-item>
    </el-breadcrumb>
    <el-table :data="currentData" @row-click="navigateToRow">
      <el-table-column prop="name" label="Name"></el-table-column>
      <!-- 更多列 -->
    </el-table>
  </div>
</template>

<script>
const data = [
  {
    id: 1,
    name: 'Parent 1',
    children: [
      {
        id: 11,
        name: 'Child 1',
        children: [
          { id: 111, name: 'Grandchild 1', children: [] },
          { id: 112, name: 'Grandchild 2', children: [] }
        ]
      },
      {
        id: 12,
        name: 'Child 2',
        children: []
      }
    ]
  },
  // 更多层级...
];

export default { data() { return { data, currentData: data, breadcrumbs: ['Home'], breadcrumbPaths: [[]] }; }, methods: { navigateToRow(row) { if (row.children && row.children.length > 0) { this.currentData = row.children; this.breadcrumbs.push(row.name); this.breadcrumbPaths.push([...this.breadcrumbPaths[this.breadcrumbPaths.length - 1], row]); } }, jumpTo(index) { const path = this.breadcrumbPaths[index]; let currentData = data; path.forEach(row => { currentData = row.children; }); this.currentData = currentData; this.breadcrumbs = this.breadcrumbs.slice(0, index + 1); this.breadcrumbPaths = this.breadcrumbPaths.slice(0, index + 1); } } }; </script>

解释:

  1. 数据模型: 我们定义了一个嵌套的 data 结构,代表了不同层级的数据。

  2. Vue 组件: 我们在组件中定义了 currentDatabreadcrumbs,前者用于显示当前层级的数据,后者用于存储当前的面包屑路径。

  3. 方法:

    • navigateToRow: 当表格行被点击时调用,检查该行是否拥有子数据,如果有,则更新 currentData 并在面包屑中添加新项。
    • jumpTo: 当面包屑项被点击时调用,它会根据面包屑的索引跳回到相应的层级。

通过这种方式,你就可以在 Vue.js 应用中实现一个具有面包屑导航的表格下钻功能,用户可以轻松地在不同层级之间跳转。这个示例是一个基本的实现,你可以根据具体需求进行扩展,比如添加更多的交互细节、优化UI设计等。

posted @ 2024-07-18 10:03  夏小夏吖  阅读(30)  评论(0编辑  收藏  举报