uniapp生成表格
uniapp 生成表格的方法
在 uniapp 中生成表格可以通过多种方式实现,以下是几种常见的方法:
使用 <table> 标签
uniapp 支持 HTML5 的 <table> 标签,可以直接在模板中使用:
<template>
<view>
<table>
<tr>
<th>姓名</th>
<th>年龄</th>
<th>职业</th>
</tr>
<tr v-for="(item, index) in tableData" :key="index">
<td>{{ item.name }}</td>
<td>{{ item.age }}</td>
<td>{{ item.job }}</td>
</tr>
</table>
</view>
</template>
<script>
export default {
data() {
return {
tableData: [
{ name: '张三', age: 25, job: '工程师' },
{ name: '李四', age: 30, job: '设计师' },
{ name: '王五', age: 28, job: '产品经理' }
]
}
}
}
</script>
使用 <uni-table> 组件
uniapp 官方提供了 <uni-table> 组件,可以更方便地生成表格:

<template>
<view>
<uni-table>
<uni-tr>
<uni-th>姓名</uni-th>
<uni-th>年龄</uni-th>
<uni-th>职业</uni-th>
</uni-tr>
<uni-tr v-for="(item, index) in tableData" :key="index">
<uni-td>{{ item.name }}</uni-td>
<uni-td>{{ item.age }}</uni-td>
<uni-td>{{ item.job }}</uni-td>
</uni-tr>
</uni-table>
</view>
</template>
使用第三方表格组件
uniapp 生态中有许多第三方表格组件,如 mescroll-uni、uView 等,可以提供更丰富的功能:
<template>
<view>
<u-table :columns="columns" :data="tableData"></u-table>
</view>
</template>
<script>
export default {
data() {
return {
columns: [
{ title: '姓名', key: 'name' },
{ title: '年龄', key: 'age' },
{ title: '职业', key: 'job' }
],
tableData: [
{ name: '张三', age: 25, job: '工程师' },
{ name: '李四', age: 30, job: '设计师' },
{ name: '王五', age: 28, job: '产品经理' }
]
}
}
}
</script>
自定义表格样式

如果需要更灵活的表格样式,可以通过 CSS 自定义:
<template>
<view class="custom-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.job }}</view>
</view>
</view>
</template>
<style>
.custom-table {
width: 100%;
border: 1px solid #eee;
}
.table-row {
display: flex;
border-bottom: 1px solid #eee;
}
.table-cell {
flex: 1;
padding: 10px;
text-align: center;
}
.header {
font-weight: bold;
background-color: #f5f5f5;
}
</style>
动态生成表格数据
表格数据通常从后端 API 获取:
<template>
<view>
<table>
<tr>
<th>姓名</th>
<th>年龄</th>
<th>职业</th>
</tr>
<tr v-for="(item, index) in tableData" :key="index">
<td>{{ item.name }}</td>
<td>{{ item.age }}</td>
<td>{{ item.job }}</td>
</tr>
</table>
</view>
</template>
<script>
export default {
data() {
return {
tableData: []
}
},
onLoad() {
this.fetchTableData()
},
methods: {
async fetchTableData() {
const res = await uni.request({
url: 'https://example.com/api/table-data'
})
this.tableData = res.data
}
}
}
</script>
以上方法可以根据具体需求选择使用,uniapp 提供了多种生成表格的方式,开发者可以根据项目需求选择最适合的方案。






