Skip to content

Commit

Permalink
fix(v-memo): ensure track block when returning cached vnode (#4270)
Browse files Browse the repository at this point in the history
fix #4253
  • Loading branch information
edison1105 committed Aug 7, 2021
1 parent 3b60358 commit a211e27
Show file tree
Hide file tree
Showing 3 changed files with 12 additions and 10 deletions.
Expand Up @@ -37,7 +37,7 @@ export function render(_ctx, _cache) {
return (_openBlock(), _createElementBlock(\\"div\\", null, [
(_openBlock(true), _createElementBlock(_Fragment, null, _renderList(_ctx.list, ({ x, y }, __, ___, _cached) => {
const _memo = ([x, y === z])
if (_cached && _cached.key === x && _isMemoSame(_cached.memo, _memo)) return _cached
if (_cached && _cached.key === x && _isMemoSame(_cached, _memo)) return _cached
const _item = (_openBlock(), _createElementBlock(\\"span\\", { key: x }, \\"foobar\\"))
_item.memo = _memo
return _item
Expand All @@ -53,7 +53,7 @@ export function render(_ctx, _cache) {
return (_openBlock(), _createElementBlock(\\"div\\", null, [
(_openBlock(true), _createElementBlock(_Fragment, null, _renderList(_ctx.list, ({ x, y }, __, ___, _cached) => {
const _memo = ([x, y === _ctx.z])
if (_cached && _cached.key === x && _isMemoSame(_cached.memo, _memo)) return _cached
if (_cached && _cached.key === x && _isMemoSame(_cached, _memo)) return _cached
const _item = (_openBlock(), _createElementBlock(\\"div\\", { key: x }, [
_createElementVNode(\\"span\\", null, \\"foobar\\")
]))
Expand Down
2 changes: 1 addition & 1 deletion packages/compiler-core/src/transforms/vFor.ts
Expand Up @@ -209,7 +209,7 @@ export const transformFor = createStructuralDirectiveTransform(
...(keyExp ? [` && _cached.key === `, keyExp] : []),
` && ${context.helperString(
IS_MEMO_SAME
)}(_cached.memo, _memo)) return _cached`
)}(_cached, _memo)) return _cached`
]),
createCompoundExpression([`const _item = `, childBlock as any]),
createSimpleExpression(`_item.memo = _memo`),
Expand Down
16 changes: 9 additions & 7 deletions packages/runtime-core/src/helpers/withMemo.ts
Expand Up @@ -7,23 +7,25 @@ export function withMemo(
index: number
) {
const cached = cache[index] as VNode | undefined
if (cached && isMemoSame(cached.memo!, memo)) {
// make sure to let parent block track it when returning cached
if (isBlockTreeEnabled > 0 && currentBlock) {
currentBlock.push(cached)
}
if (cached && isMemoSame(cached, memo)) {
return cached
}
const ret = render()
ret.memo = memo
return (cache[index] = ret)
}

export function isMemoSame(prev: any[], next: any[]) {
export function isMemoSame(cached: VNode, memo: any[]) {
const prev: any[] = cached.memo!
for (let i = 0; i < prev.length; i++) {
if (prev[i] !== next[i]) {
if (prev[i] !== memo[i]) {
return false
}
}

// make sure to let parent block track it when returning cached
if (isBlockTreeEnabled > 0 && currentBlock) {
currentBlock.push(cached)
}
return true
}

0 comments on commit a211e27

Please sign in to comment.