vue 2.X +iview4.0 table組件多選分頁回顯

在寫業(yè)務(wù)的時候難免遇到table多選,翻頁后需要回顯的功能,以前寫react antd 組件是提供一個所有保存rowKeys的數(shù)組保存的,自動回顯,然后可以自定義key,比如用每條數(shù)據(jù)的id做key,一般后端給的數(shù)據(jù)的id都是唯一的,所以沒有問題。
但是在寫vue的時候發(fā)現(xiàn),不管是element還是iview 都沒有提供自定義table數(shù)據(jù)key的功能,所以做回顯自能自己寫邏輯,因為最近在用iview 就用iview做例子

on-select 在多選模式下有效,選中某一項時觸發(fā) selection:已選項數(shù)據(jù) row:剛選擇的項數(shù)據(jù)

on-select-cancel 在多選模式下有效,取消選中某一項時觸發(fā) selection:已選項數(shù)據(jù)
row:取消選擇的項數(shù)據(jù)

需要用到的就是這兩個方法,然后加上

通過給 columns 數(shù)據(jù)設(shè)置一項,指定 type: 'selection',即可自動開啟多選功能。
給 data 項設(shè)置特殊 key _checked: true 可以默認(rèn)選中當(dāng)前項。

下面上代碼

<Table
        :columns="tableColumn"
        :data="tableData"
        ref="table"
        @on-select="selectChange"
        @on-select-cancel="selectChangeCancel"
      >
</Table>
// 勾選
 selectChangeOut(el, row) {
      let productData = JSON.parse(JSON.stringify(this.productData))
      productData.push(row)
      this.productData = productData
  
  },
// 取消選擇
 selectChangeCancel(el, row) {
      let productData = JSON.parse(JSON.stringify(this.productData))
      let newProductData = productData.filter(item => {
        return item.id != row.id
      })
      this.productData = newProductData
  },
// 回顯勾選
    selectedTrue(selects) {
      setTimeout(() => {
        let tableData = JSON.parse(JSON.stringify(this.tableData))
        this.productData.forEach(el => {
          let index = tableData.findIndex(i => {
            return el.id == i.id
          })
          if (index != -1) {
            this.$refs.table.objData[index]._isChecked = true
          }
        })
      }, 0)
    },

在每次分頁請求之后調(diào)用這個方法就好了,為什么要setTimeout,是因為如果不加,那么這個方法執(zhí)行會在table數(shù)據(jù)填充之前 ,找不到able的objData屬性。各位有其他更好的回顯方法也可以試試
回顯方法個人建議,直接放在 請求后端接口的方法里面,比如我個人喜歡用getData做請求接口函數(shù)名

// 調(diào)接口查詢數(shù)據(jù)
getData: async function() {
      let res = await xxxx()
      this.selectedTrue()
  }

以上

這么寫會有一個bug 就是點擊全選的時候,數(shù)據(jù)并不能保存在 this.productData里面,可以自己再寫一個全選的,或者用on-selection-change換掉on-select 邏輯就大家自己寫了哦

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容