element-ui table 的翻页记忆选中

公司中台项目刚开始开发,用了vue+element,需要许多前置调研,table的翻译记忆选中就是其中之一。

template:

<el-table 
  :ref="tableRef"
  :data="tableData" 
  @select-all="handleSelect"
  @select="handleSelect"  
>
  <el-table-column
    type="selection"
    width="55"
  >
  </el-table-column>
  <el-table-column
    v-for="item in tableColumns"
    :key="item"
    :property="item.property" 
    :label="item.label" 
    :width="item.width"
  >
  </el-table-column>
</el-table>
<el-pagination
  layout="total,prev, pager, next, jumper"
  :page-size="5"
  @current-change="handleCurrentChange"
  :current-page.sync="currentPage"
  :total="10">
</el-pagination>

tableRef 是上级传入的props,为了区分多个表格同时存在的情况。

tableData 和 tableColumns 都是从组件外传入的,不难理解。

将 select 和 select-all 事件集中到同一个事件 handleSelect, 因为用到的数据都是该事件返回的 row 。

翻页的 currentPage 和 handleCurrentChange 是翻页组件的当前页和页码改变的事件。

methods:

handleSelect(val){
  const hasSave = this.selected.find(item => {
    return item.page === this.currentPage
  })
  if(hasSave){
    hasSave.rows = this.tableData.filter(item => {
      return val.includes(item)
    })
  }else{
    this.selected.push({
      page: this.currentPage,
      rows: val
    })
  }  
},
handleCurrentChange(val){
  // 向上传递事件
  this.$emit('pageChange',val)
},
toggleSelection(){
  this.$refs[this.tableRef].clearSelection()
  const target = this.selected.find(item => {
    return item.page === this.currentPage
  })
  if(!target) return
  const rows = target.rows
  if(rows && rows.length>0){
    this.$nextTick(()=>{
      rows.forEach(row => {
        this.$refs[this.tableRef].toggleRowSelection(row)
      })  
    })
  }
},
getSelected(){
  if(this.selected.length === 0){
    return []
  }
  let result = []
  this.selected.forEach(item => {
    result = [...result,...item.rows]
  })
  return result
}

 

当页码改变时,传递数据到外层请求数据,在本组件watch tableData的变化

watch: {
  tableData(){
    this.toggleSelection()
  }
},

 

最后获取执行具体逻辑就不解释了,都是比较简单的,有需要可以留言或者私信。

 

posted @ 2019-12-30 16:00  lisiyuan  阅读(2833)  评论(0编辑  收藏  举报