微信小程序封装公共组件table表格

由于小程序可能不止一个页面需要用表格展示数据,所以在components里封装公共组件,如下图:
微信小程序封装公共组件table表格_第1张图片

  1. 首先,在myTable组件的index.wxml写好布局,这里主要是表格头部,表格内容则通过slot插槽插入进来


  

    
      
        {{item.title}}
      
    

    

      

    

  

  1. 表格的每一列是一个公共组件myTableCol,其index.wxml内容如下:


  
    
      {{item}}
    
  

  
    
      
        {{item}}
      
    
  

分为两种情况,传了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,
      })

    },

  }
})
  1. 在页面引用,需要先在使用的页面的index.json文件中写上:
  "usingComponents": {
    "myTable":"../../components/myTable/index",
    "myTableCol":"../../components/myTableCol/index"
  }

然后在index.wxml文件里使用组件,例如:

      

        
          
          
          
          
          
        

      

父组件的index.js中,getEmpOperateIndex方法接收公共组件传过来的参数:

  getEmpOperateIndex(e) {
  // e.detail.row 表示点了哪一行
    if (e.detail.index == 0) {
      // 点了编辑
    } else if (e.detail.index == 1) {
      // 点了删除
   }
}

4.完成之后,效果如下图:
微信小程序封装公共组件table表格_第2张图片

你可能感兴趣的:(微信小程序封装公共组件table表格)