簡體   English   中英

如何在不更新所有其他項目的情況下移動數組中的項目?

[英]How to move an item in an array without updating all the others?

我有一個由對象組成的數組,例如:

const items = [
    { id: 0, title: 'Object 1', sort: 0 },
    { id: 1, title: 'Object 2', sort: 1 },
    { id: 2, title: 'Object 3', sort: 2 },
    { id: 3, title: 'Object 4', sort: 3 },
    { id: 4, title: 'Object 5', sort: 4 },
    { id: 5, title: 'Object 6', sort: 5 },
    { id: 6, title: 'Object 7', sort: 6 },
    { id: 7, title: 'Object 8', sort: 7 },
    { id: 8, title: 'Object 9', sort: 8 }
]

使用拖動庫(通過 VueDragguable 的 Sortable.js),我收到“onChange”事件,其中包含以下詳細信息:

  • 元素:移動的元素,例如, { id: 2, title: 'Object 3', sort: 2 }
  • newIndex:這個元素新的position,比如6
  • oldIndex:舊的position,這里是3

當觸發change事件時(特別是移動,而不是addremove ),我想更新受更改影響的對象中的sort屬性,方法是修改最少數量的對象(以減少數據庫中的寫入次數)。

我怎么能那樣做?

注意:這里的“排序”參數是任意的。 如果有更好的方法,我可以相應地更新代碼。

在您的情況下,您只需使用 splice 方法將數組中的項目移動到正確的位置,然后檢查您的項目是否在正確的位置。

您可以使用 filter 方法與這些索引進行比較來找到所有錯誤的項目。

 const items = [ { id: 0, title: 'Object 1', sort: 0 }, { id: 1, title: 'Object 2', sort: 1 }, { id: 2, title: 'Object 3', sort: 2 }, { id: 3, title: 'Object 4', sort: 3 }, { id: 4, title: 'Object 5', sort: 4 }, { id: 5, title: 'Object 6', sort: 5 }, { id: 6, title: 'Object 7', sort: 6 }, { id: 7, title: 'Object 8', sort: 7 }, { id: 8, title: 'Object 9', sort: 8 } ] const event = { element: { id: 2, title: 'Object 3', sort: 2 }, newIndex: 6, oldIndex: 2 } // removing the item items.splice(event.oldIndex, 1) //replacing it items.splice(event.newIndex - 1, 0, event.element) const itemsToUpdateInDatabase = items.filter((item, index) => item.sort.== index) console.log(itemsToUpdateInDatabase)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM