Skip to content

Commit 4c7aca6

Browse files
fix: fixed 'childNodes' index error (#205)
1 parent da43c3d commit 4c7aca6

File tree

1 file changed

+29
-4
lines changed

1 file changed

+29
-4
lines changed

src/useDraggable.ts

+29-4
Original file line numberDiff line numberDiff line change
@@ -132,7 +132,7 @@ export function useDraggable<T>(
132132
*/
133133
export function useDraggable<T>(...args: any[]): UseDraggableReturn {
134134
const vm = getCurrentInstance()?.proxy
135-
135+
let currentNodes: Node[] | null = null
136136
const el = args[0]
137137
let [, list, options] = args
138138

@@ -153,10 +153,12 @@ export function useDraggable<T>(...args: any[]): UseDraggableReturn {
153153
* @param {DraggableEvent} evt - DraggableEvent
154154
*/
155155
function onStart(evt: DraggableEvent) {
156-
const data = unref(unref(list)?.[evt.oldIndex!])
156+
const { from, oldIndex, item } = evt
157+
currentNodes = Array.from(from.childNodes)
158+
const data = unref(unref(list)?.[oldIndex!])
157159
const clonedData = clone(data)
158160
setCurrentData(data, clonedData)
159-
evt.item[CLONE_ELEMENT_KEY] = clonedData
161+
item[CLONE_ELEMENT_KEY] = clonedData
160162
}
161163

162164
/**
@@ -214,9 +216,32 @@ export function useDraggable<T>(...args: any[]): UseDraggableReturn {
214216
moveArrayElement(unref(list), oldIndex!, newIndex!)
215217
}
216218

217-
function onEnd() {
219+
function onEnd(e: DraggableEvent) {
220+
const { newIndex, oldIndex, from, to } = e
221+
let error: Error | null = null
222+
const isSameIndex = newIndex === oldIndex && from === to
223+
try {
224+
//region #202
225+
if (isSameIndex) {
226+
let oldNode: Node | null = null
227+
currentNodes?.some((node, index) => {
228+
if (oldNode && currentNodes?.length !== to.childNodes.length) {
229+
from.insertBefore(oldNode, node.nextSibling)
230+
return true
231+
}
232+
const _node = to.childNodes[index]
233+
oldNode = to?.replaceChild(node, _node)
234+
})
235+
}
236+
//endregion
237+
} catch (e) {
238+
error = e
239+
} finally {
240+
currentNodes = null
241+
}
218242
nextTick(() => {
219243
setCurrentData()
244+
if (error) throw error
220245
})
221246
}
222247

0 commit comments

Comments
 (0)