因为小程序可能不止一个页面须要用表格展现数据,所以在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.实现之后,成果如下图: