uniapp 表格组件如何使用

在uniapp中如何使用表格组件?是否需要引入第三方库,还是uniapp自带了表格组件?能否提供一个简单的示例代码,说明如何实现基本的数据展示和样式调整?

2 回复

使用uni-app表格组件,推荐使用uni-table。首先安装uni-table插件,然后在页面中引入:

<uni-table>
  <uni-tr>
    <uni-th>姓名</uni-th>
    <uni-th>年龄</uni-th>
  </uni-tr>
  <uni-tr>
    <uni-td>张三</uni-td>
    <uni-td>25</uni-td>
  </uni-tr>
</uni-table>

记得在pages.json中引入组件,或全局注册。支持自定义样式和事件处理。


在 UniApp 中,没有内置的表格组件,但可以通过以下方式实现表格功能:

1. 使用 viewflex 布局手动构建表格

<template>
  <view class="table">
    <!-- 表头 -->
    <view class="table-row header">
      <view class="table-cell">姓名</view>
      <view class="table-cell">年龄</view>
      <view class="table-cell">城市</view>
    </view>
    <!-- 表格数据 -->
    <view class="table-row" v-for="(item, index) in tableData" :key="index">
      <view class="table-cell">{{ item.name }}</view>
      <view class="table-cell">{{ item.age }}</view>
      <view class="table-cell">{{ item.city }}</view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      tableData: [
        { name: '张三', age: 25, city: '北京' },
        { name: '李四', age: 30, city: '上海' }
      ]
    }
  }
}
</script>

<style scoped>
.table {
  width: 100%;
  border: 1px solid #ddd;
}
.table-row {
  display: flex;
  border-bottom: 1px solid #ddd;
}
.table-cell {
  flex: 1;
  padding: 8px;
  text-align: center;
  border-right: 1px solid #ddd;
}
.table-cell:last-child {
  border-right: none;
}
.header {
  background-color: #f5f5f5;
  font-weight: bold;
}
</style>

2. 使用第三方组件库

推荐使用 uni-tableuView UI 等第三方库:

安装 uView UI:

npm install uview-ui

使用示例:

<template>
  <u-table>
    <u-tr>
      <u-th>姓名</u-th>
      <u-th>年龄</u-th>
      <u-th>城市</u-th>
    </u-tr>
    <u-tr v-for="(item, index) in tableData" :key="index">
      <u-td>{{ item.name }}</u-td>
      <u-td>{{ item.age }}</u-td>
      <u-td>{{ item.city }}</u-td>
    </u-tr>
  </u-table>
</template>

3. 使用 uni-list 组件(简单列表)

适用于简单表格:

<uni-list>
  <uni-list-item 
    v-for="(item, index) in tableData" 
    :key="index" 
    :title="item.name" 
    :note="`年龄: ${item.age}, 城市: ${item.city}`"
  />
</uni-list>

注意事项:

  1. 复杂表格建议使用第三方组件库
  2. 手动构建时注意样式兼容性
  3. 大数据量建议使用虚拟滚动

选择方案时根据项目复杂度决定,简单表格可用手动构建,复杂需求推荐使用 uView UI 等成熟组件库。

回到顶部