您可以使用Vue中的v-if和v-for指令来实现树形表格的展开和收缩功能。

  1. 首先,在表格中添加一个“展开”或“收缩”按钮,并为其绑定一个方法:
<template>
  <div>
    <table>
      <thead>
        <tr>
          <th>名称</th>
          <th>类型</th>
          <th>大小</th>
          <th>操作</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="item in data" :key="item.id">
          <td>{{ item.name }}</td>
          <td>{{ item.type }}</td>
          <td>{{ item.size }}</td>
          <td>
            <button @click="toggle(item)">
              {{ item.children && item.children.length ? '收缩' : '展开' }}
            </button>
          </td>
        </tr>
      </tbody>
    </table>
  </div>
</template>

<script>
export default {
  data() {
    return {
      data: [
        {
          id: 1,
          name: '文件夹1',
          type: '文件夹',
          size: '-',
          children: [
            {
              id: 2,
              name: '文件1',
              type: '文件',
              size: '10KB',
            },
            {
              id: 3,
              name: '文件2',
              type: '文件',
              size: '20KB',
            },
          ],
        },
        {
          id: 4,
          name: '文件夹2',
          type: '文件夹',
          size: '-',
          children: [
            {
              id: 5,
              name: '文件3',
              type: '文件',
              size: '30KB',
            },
          ],
        },
      ],
    };
  },
  methods: {
    toggle(item) {
      if (item.children && item.children.length) {
        item.children = null;
      } else {
        // 模拟异步加载子节点
        setTimeout(() => {
          item.children = [
            {
              id: 6,
              name: '文件4',
              type: '文件',
              size: '40KB',
            },
          ];
        }, 1000);
      }
    },
  },
};
</script>
  1. 然后,在方法中判断当前节点是否有子节点,如果有就将其设置为null,没有则异步加载子节点,并将其设置为一个数组。

  2. 最后,在表格中使用v-if指令判断当前节点是否有子节点,如果有就使用v-for指令遍历子节点。

<template>
  <div>
    <table>
      <thead>
        <tr>
          <th>名称</th>
          <th>类型</th>
          <th>大小</th>
          <th>操作</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="item in data" :key="item.id">
          <td>{{ item.name }}</td>
          <td>{{ item.type }}</td>
          <td>{{ item.size }}</td>
          <td>
            <button @click="toggle(item)">
              {{ item.children && item.children.length ? '收缩' : '展开' }}
            </button>
          </td>
        </tr>
        <tr v-if="item.children && item.children.length" v-for="child in item.children" :key="child.id">
          <td>{{ child.name }}</td>
          <td>{{ child.type }}</td>
          <td>{{ child.size }}</td>
          <td></td>
        </tr>
      </tbody>
    </table>
  </div>
</template>

这样,您就可以实现一个简单的树形表格,并实现展开和收缩功能。

vue 树形 表格 按钮 展开收缩

原文地址: https://www.cveoy.top/t/topic/by5m 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录