Skip to content

Commit

Permalink
fix: v-for update on move (#79)
Browse files Browse the repository at this point in the history
  • Loading branch information
nooooooom committed Sep 14, 2021
1 parent 167c49d commit 9af4ea3
Showing 1 changed file with 14 additions and 9 deletions.
23 changes: 14 additions & 9 deletions src/directives/for.ts
Expand Up @@ -124,38 +124,43 @@ export const _for = (el: Element, exp: string, ctx: Context) => {
blocks = childCtxs.map((s) => mountBlock(s, anchor))
mounted = true
} else {
const nextBlocks: Block[] = []
for (let i = 0; i < blocks.length; i++) {
if (!keyToIndexMap.has(blocks[i].key)) {
blocks[i].remove()
}
}


const nextBlocks: Block[] = []
let i = childCtxs.length
let nextBlock: Block | undefined
let prevMovedBlock: Block | undefined
while (i--) {
const childCtx = childCtxs[i]
const oldIndex = prevKeyToIndexMap.get(childCtx.key)
const next = childCtxs[i + 1]
const nextBlockOldIndex = next && prevKeyToIndexMap.get(next.key)
const nextBlock =
nextBlockOldIndex == null ? undefined : blocks[nextBlockOldIndex]
let block
if (oldIndex == null) {
// new
nextBlocks[i] = mountBlock(
block = mountBlock(
childCtx,
nextBlock ? nextBlock.el : anchor
)
} else {
// update
const block = (nextBlocks[i] = blocks[oldIndex])
block = blocks[oldIndex]
Object.assign(block.ctx.scope, childCtx.scope)
if (oldIndex !== i) {
// moved
if (blocks[oldIndex + 1] !== nextBlock) {
if (
blocks[oldIndex + 1] !== nextBlock ||
// If the next has moved, it must move too
prevMovedBlock === nextBlock
) {
prevMovedBlock = block
block.insert(parent, nextBlock ? nextBlock.el : anchor)
}
}
}
nextBlocks.unshift(nextBlock = block)
}
blocks = nextBlocks
}
Expand Down

0 comments on commit 9af4ea3

Please sign in to comment.