Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 9e78eda

Browse files
authored
fix(useSortable): wrong order of elements (#4332)
1 parent 1bb547e commit 9e78eda

File tree

2 files changed

+34
-2
lines changed

2 files changed

+34
-2
lines changed

packages/integrations/useSortable/index.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -102,7 +102,7 @@ import { moveArrayElement } from '@vueuse/integrations/useSortable'
102102
useSortable(el, list, {
103103
onUpdate: (e) => {
104104
// do something
105-
moveArrayElement(list.value, e.oldIndex, e.newIndex)
105+
moveArrayElement(list.value, e.oldIndex, e.newIndex, e)
106106
// nextTick required here as moveArrayElement is executed in a microtask
107107
// so we need to wait until the next tick until that is finished.
108108
nextTick(() => {

packages/integrations/useSortable/index.ts

Lines changed: 33 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,7 @@ export function useSortable<T>(
4646

4747
const defaultOptions: Options = {
4848
onUpdate: (e) => {
49-
moveArrayElement(list, e.oldIndex!, e.newIndex!)
49+
moveArrayElement(list, e.oldIndex!, e.newIndex!, e)
5050
},
5151
}
5252

@@ -80,11 +80,43 @@ export function useSortable<T>(
8080
}
8181
}
8282

83+
/**
84+
* Inserts a element into the DOM at a given index.
85+
* @param parentElement
86+
* @param element
87+
* @param {number} index
88+
* @see https://github.com/Alfred-Skyblue/vue-draggable-plus/blob/a3829222095e1949bf2c9a20979d7b5930e66f14/src/utils/index.ts#L81C1-L94C2
89+
*/
90+
export function insertNodeAt(
91+
parentElement: Element,
92+
element: Element,
93+
index: number,
94+
) {
95+
const refElement = parentElement.children[index]
96+
parentElement.insertBefore(element, refElement)
97+
}
98+
99+
/**
100+
* Removes a node from the DOM.
101+
* @param {Node} node
102+
* @see https://github.com/Alfred-Skyblue/vue-draggable-plus/blob/a3829222095e1949bf2c9a20979d7b5930e66f14/src/utils/index.ts#L96C1-L102C2
103+
*/
104+
export function removeNode(node: Node) {
105+
if (node.parentNode)
106+
node.parentNode.removeChild(node)
107+
}
108+
83109
export function moveArrayElement<T>(
84110
list: MaybeRefOrGetter<T[]>,
85111
from: number,
86112
to: number,
113+
e: Sortable.SortableEvent | null = null,
87114
): void {
115+
if (e != null) {
116+
removeNode(e.item)
117+
insertNodeAt(e.from, e.item, from)
118+
}
119+
88120
const _valueIsRef = isRef(list)
89121
// When the list is a ref, make a shallow copy of it to avoid repeatedly triggering side effects when moving elements
90122
const array = _valueIsRef ? [...toValue(list)] : toValue(list)

0 commit comments

Comments
 (0)