ElementUI表格排序后刪除元素錯亂:scope.$index失效導(dǎo)致刪除錯誤如何解決?

ElementUI表格排序后刪除元素錯亂:scope.$index失效導(dǎo)致刪除錯誤如何解決?

elementui表格排序與刪除沖突:scope.$index失效引發(fā)的刪除錯誤及解決方案

在使用ElementUI開發(fā)過程中,表格排序和刪除操作的結(jié)合常常會引發(fā)問題。本文分析一個實際案例:ElementUI表格排序后,點擊刪除按鈕導(dǎo)致元素刪除錯亂,并非刪除預(yù)期元素,而是隨機刪除。 盡管打印的索引值看似正確,但仍導(dǎo)致錯誤。僅當表格僅剩一個元素時,刪除操作才正常。

問題描述:

項目中基于ElementUI的表格組件出現(xiàn)問題:表格數(shù)據(jù)排序后,點擊刪除按鈕,刪除操作并非作用于預(yù)期元素,而是隨機刪除。奇怪的是,打印的索引值rowindex看似正確。只有當表格僅剩一個元素時,刪除才正常執(zhí)行。

代碼片段:

  • 刪除函數(shù):
async ondeldtlgood(rowindex) {     console.log(rowindex);     this.addform.dtlgoods.splice(rowindex, 1); },
  • 排序函數(shù):
customsort(a, b) {     const acode = a.goodscode;     const bcode = b.goodscode;     if (acode > bcode) {         return 1;     }     return 0; },
  • 刪除按鈕:
<el-table-column label="操作" width="120">     <template slot-scope="scope">         <el-button type="danger" @click="ondeldtlgood(scope.$index)">刪除</el-button>     </template> </el-table-column>

問題排查:

開發(fā)者嘗試阻止事件冒泡、重寫排序函數(shù)、移除async修飾符、添加await關(guān)鍵字等方法,均無效。

問題根源及解決方案:

問題在于scope.$index的實時性。scope.$index并非在點擊刪除時獲取,而是在表格渲染時確定。排序后,數(shù)據(jù)順序改變,但scope.$index值不變。因此,打印的rowindex看似正確,實為排序前的索引值。刪除操作使用舊索引值,導(dǎo)致刪除錯誤元素。只有單個元素時,索引值不變,刪除才正常。這并非隨機刪除,而是索引值與數(shù)據(jù)位置不匹配。

解決方案:

避免使用scope.$index進行刪除操作。 推薦使用數(shù)據(jù)項本身的唯一標識符(例如ID)來定位要刪除的元素。 修改刪除函數(shù)如下:

async ondeldtlgood(row) {     const index = this.addform.dtlgoods.findIndex(item => item.id === row.id); // 使用唯一標識符id     if (index !== -1) {         this.addform.dtlgoods.splice(index, 1);     } },

并修改刪除按鈕的點擊事件

<el-button type="danger" @click="ondeldtlgood(scope.row)">刪除</el-button>

通過使用數(shù)據(jù)項的唯一標識符,確保刪除操作始終作用于正確的元素,解決了排序后刪除錯亂的問題。 這是一種更可靠和健壯的處理方法。

? 版權(quán)聲明
THE END
喜歡就支持一下吧
點贊7 分享