在 Element Plus 的 el-table 組件中,使用?scope.index
?是不準確的。正確的索引屬性應該是?scope.$index
。你的代碼需要調整為:
vue
復制
下載
<el-button type="primary" size="default" text @click="onModifyClick(scope.$index, scope.row)" >編輯</el-button>
具體說明:
-
索引屬性名錯誤:
-
Element Plus 的表格作用域插槽暴露的是?
$index
?屬性(帶$符號),不是?index
-
scope.index
?會得到 undefined,實際應該使用?scope.$index
-
-
推薦驗證方式:
vue
復制
下載
<template #default="scope">{{ console.log(scope) }} <!-- 打印查看完整 scope 對象 --> </template>
scope 對象
-
需要注意的特殊情況:
-
當表格存在多級表頭時,
$index
?對應的是數據數組的索引 -
如果表格數據被過濾/排序后,
$index
?反映的是當前顯示行的索引,不是原始數據索引 -
對于需要絕對索引的場景,建議直接使用行數據的唯一標識(如你刪除操作中使用的 materialNo)
-
-
更健壯的寫法建議:
vue
復制
下載
<el-button type="primary" size="default" text @click="onModifyClick(scope.$index, { ...scope.row, $index: scope.$index })" >編輯</el-button>
完整修正后的代碼:
vue
復制
下載
<el-table-column label="操作" header-align="center" align="center" fixed="right" width="120" ><template #default="scope"><el-buttontype="primary"size="default"text@click="onModifyClick(scope.$index, scope.row)">編輯</el-button><el-buttontype="danger"size="default"text@click="onDeleteClick(scope.row.materialNo)">刪除</el-button></template> </el-table-column>
如果發現索引值不符合預期,請檢查:
-
el-table 是否設置了?
row-key
-
表格數據是否是響應式數據(ref/reactive)
-
是否使用了過濾/排序功能(這會改變顯示行的索引)