由于小程序可能不止一个页面需要用表格展示数据,所以在components里封装公共组件,如下图:
- 首先,在myTable组件的index.wxml写好布局,这里主要是表格头部,表格内容则通过slot插槽插入进来
<view class="my-table-wrap">
<view class="my-table">
<view class="my-table-thead">
<view class="my-tr">
<view
class="my-th"
style="width:{{item.width}}"
wx:for-items="{{tableHeadData}}"
wx:key="index"
>{{item.title}}</view>
</view>
</view>
<view class="my-table-tbody">
<slot></slot>
</view>
</view>
</view>
- 表格的每一列是一个公共组件myTableCol,其index.wxml内容如下:
<view style="height: 100%;">
<view wx:if="{{prop}}" class="my-table-tbody-col">
<block wx:for-items="{{list}}" wx:key="index">
<view class="my-td">{{item}}</view>
</block>
</view>
<view wx:else class="my-table-tbody-col">
<view class="my-td-op" wx:for="{{tableData}}" wx:key="id" wx:for-index="row">
<block wx:for-items="{{operateList}}" wx:key="index">
<view class="blueviolet-edit" bindtap="operate" data-row="{{row}}" data-index="{{index}}">{{item}}</view>
</block>
</view>
</view>
</view>
分为两种情况,传了prop的普通列和操作列,myTableCol的index.js内容如下:
Component({
properties: {
prop: {
type: String
},
label: {
type: String
},
width: {
type: String
},
tableData: {
type: Array,
observer: function(newVal, oldVal) {
// 当编辑表格时,会重新请求表格数据,这里就会渲染
let list = newVal.map(i=> i[this.properties.prop])
this.setData({list})
}
},
operate: {
type: String
},
},
pageLifetimes: {
show() {
if(this.properties.prop){
// 筛选出每一普通列的数据
let list = this.properties.tableData.map(i=> i[this.properties.prop])
this.setData({list})
}else{
// 操作列
let operateList = this.properties.operate.split(',')
this.setData({operateList})
}
}
},
data: {
list:[],
operateList:[],
},
methods: {
operate(e){
// 操作列的点击事件,需要传给父组件两个信息:点了表格的哪一行(row),点了按钮的哪一个(index)
this.triggerEvent('getOperateIndex', {
row: e.target.dataset.row,
index: e.target.dataset.index,
})
},
}
})
- 在页面引用,需要先在使用的页面的index.json文件中写上:
"usingComponents": {
"myTable":"../../components/myTable/index",
"myTableCol":"../../components/myTableCol/index"
}
然后在index.wxml文件里使用组件,例如:
<view class="table">
<myTable tableHeadData="{{empTableHeadData}}">
<myTableCol tableData="{{empList}}" prop="nickname" style="width:20%"></myTableCol>
<myTableCol tableData="{{empList}}" prop="mobile" style="width:30%"></myTableCol>
<myTableCol tableData="{{empList}}" prop="job" style="width:20%"></myTableCol>
<myTableCol tableData="{{empList}}" prop="state" style="width:15%"></myTableCol>
<myTableCol tableData="{{empList}}" operate="编辑,删除" style="width:15%" bind:getOperateIndex="getEmpOperateIndex"></myTableCol>
</myTable>
</view>
父组件的index.js中,getEmpOperateIndex方法接收公共组件传过来的参数:
getEmpOperateIndex(e) {
// e.detail.row 表示点了哪一行
if (e.detail.index == 0) {
// 点了编辑
} else if (e.detail.index == 1) {
// 点了删除
}
}
4.完成之后,效果如下图:
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。