【问题标题】:How to move an item in an array without updating all the others?如何在不更新所有其他项目的情况下移动数组中的项目?
【发布时间】:2022-12-15 12:50:32
【问题描述】:

我有一个由对象组成的数组,例如:

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”事件,其中包含以下详细信息:

  • element:移动的元素,例如{ id: 2, title: 'Object 3', sort: 2 }
  • newIndex:这个元素的新位置,比如6
  • oldIndex:旧位置,这里,3

change 事件被触发时(特别是移动,而不是 addremove),我想更新受更改影响的对象中的 sort 属性,方法是修改最少的数字对象(为了减少数据库中的写入次数)。

我怎么能那样做?

注意:这里的“排序”参数是任意的。如果有更好的方法,我可以相应地更新代码。

【问题讨论】:

  • 实际上我看到了一个数组。你的数据库中有什么数据结构?
  • 你似乎问了很多事情。如果这只是关于数组数据结构管理,那么请去掉 Sortable、Vue、DOM、onChange 事件、数据库的额外层,并将问题简化为 JavaScript。但是,如果您的问题确实是关于在 Vue 中保持列表排序,那么请专注于此,提供 HTML 以及重现您遇到的问题所需的一切。
  • 一种不同的方法是也有一个包含有序 id 列表的“父”对象,并且只更新那个对象

标签: javascript sortablejs


【解决方案1】:

在您的情况下,您只需使用 splice 方法将数组中的项目移动到正确的位置,然后检查您的项目是否在正确的位置。

您可以使用 filter 方法与这些 id 进行比较来找到所有错误的项目。

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)

【讨论】:

  • 完美的!谢谢!
猜你喜欢
  • 2017-06-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-12-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多