uni-app 表格展开组件

uni-app 表格展开组件

Image

1 回复

更多关于uni-app 表格展开组件的实战教程也可以访问 https://www.itying.com/category-93-b0.html


在uni-app中实现表格展开组件,可以通过结合Vue的组件系统和条件渲染来实现。下面是一个简单的代码示例,展示了如何实现一个基本的表格展开功能。

首先,我们定义一个基本的表格组件Table.vue,它包含一个可以展开的行。

<template>
  <view class="table">
    <view class="table-header">
      <view v-for="(header, index) in headers" :key="index">{{ header }}</view>
    </view>
    <view v-for="(row, rowIndex) in rows" :key="rowIndex" class="table-row">
      <view v-for="(cell, cellIndex) in row" :key="cellIndex" class="table-cell">
        {{ cell }}
      </view>
      <view v-if="row.details && row.showDetails" class="table-expanded-row">
        <slot :name="'expanded-' + rowIndex" :row="row.details"></slot>
      </view>
      <view class="toggle-button" @click="toggleDetails(rowIndex)">
        {{ row.showDetails ? '-' : '+' }}
      </view>
    </view>
  </view>
</template>

<script>
export default {
  props: {
    headers: Array,
    rows: Array
  },
  methods: {
    toggleDetails(rowIndex) {
      this.$set(this.rows[rowIndex], 'showDetails', !this.rows[rowIndex].showDetails);
    }
  }
};
</script>

<style>
/* 样式可以根据需要自定义 */
.table {
  width: 100%;
  border-collapse: collapse;
}
.table-header, .table-row {
  display: flex;
}
.table-cell {
  border: 1px solid #ccc;
  padding: 8px;
}
.table-expanded-row {
  padding-left: 20px;
}
.toggle-button {
  cursor: pointer;
  padding: 8px;
}
</style>

在父组件中,我们使用这个表格组件,并通过具名插槽提供展开行的内容。

<template>
  <Table :headers="headers" :rows="rows">
    <template v-for="(row, rowIndex) in rows" :key="rowIndex" v-slot:expanded-{{ rowIndex }}="details">
      <view>
        <text>Expanded Content for Row {{ rowIndex }}:</text>
        <view v-for="(detail, index) in details" :key="index">{{ detail }}</view>
      </view>
    </template>
  </Table>
</template>

<script>
import Table from './Table.vue';

export default {
  components: {
    Table
  },
  data() {
    return {
      headers: ['Name', 'Age', 'Details'],
      rows: [
        { name: 'John', age: 30, showDetails: false, details: ['Detail 1', 'Detail 2'] },
        { name: 'Jane', age: 25, showDetails: false, details: ['Detail A', 'Detail B'] }
      ]
    };
  }
};
</script>

在这个示例中,我们创建了一个Table组件,它接受headersrows作为props。每一行数据都可以有一个details属性,用于存储展开行的内容。通过点击展开按钮,可以切换showDetails状态,从而显示或隐藏展开行。父组件通过具名插槽为每一行提供展开内容。

回到顶部