Skip to content

Commit 233d191

Browse files
authored
fix(keep-alive): fix activated hook invocation on nested components (#1743)
fix #1742
1 parent 00683fc commit 233d191

File tree

2 files changed

+34
-1
lines changed

2 files changed

+34
-1
lines changed

packages/runtime-core/__tests__/components/KeepAlive.spec.ts

+30
Original file line numberDiff line numberDiff line change
@@ -165,6 +165,36 @@ describe('KeepAlive', () => {
165165
assertHookCalls(two, [1, 1, 2, 2, 0])
166166
})
167167

168+
// #1742
169+
test('should call lifecycle hooks on nested components when root component no hooks', async () => {
170+
const two = {
171+
name: 'two',
172+
data: () => ({ msg: 'two' }),
173+
render(this: any) {
174+
return h('div', this.msg)
175+
},
176+
activated: jest.fn()
177+
}
178+
const one = {
179+
name: 'one',
180+
data: () => ({ msg: 'one' }),
181+
render(this: any) {
182+
return h(two)
183+
}
184+
}
185+
186+
const toggle = ref(true)
187+
const App = {
188+
render() {
189+
return h(KeepAlive, () => (toggle.value ? h(one) : null))
190+
}
191+
}
192+
render(h(App), root)
193+
194+
expect(serializeInner(root)).toBe(`<div>two</div>`)
195+
expect(two.activated).toHaveBeenCalledTimes(1)
196+
})
197+
168198
test('should call correct hooks for nested keep-alive', async () => {
169199
const toggle2 = ref(true)
170200
one.render = () => h(KeepAlive, () => (toggle2.value ? h(two) : null))

packages/runtime-core/src/renderer.ts

+4-1
Original file line numberDiff line numberDiff line change
@@ -1265,7 +1265,7 @@ function baseCreateRenderer(
12651265
if (!instance.isMounted) {
12661266
let vnodeHook: VNodeHook | null | undefined
12671267
const { el, props } = initialVNode
1268-
const { bm, m, a, parent } = instance
1268+
const { bm, m, parent } = instance
12691269
if (__DEV__) {
12701270
startMeasure(instance, `render`)
12711271
}
@@ -1324,6 +1324,9 @@ function baseCreateRenderer(
13241324
}, parentSuspense)
13251325
}
13261326
// activated hook for keep-alive roots.
1327+
// #1742 activated hook must be accessed after first render
1328+
// since the hook may be injected by a child keep-alive
1329+
const { a } = instance
13271330
if (
13281331
a &&
13291332
initialVNode.shapeFlag & ShapeFlags.COMPONENT_SHOULD_KEEP_ALIVE

0 commit comments

Comments
 (0)