Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit 2e39f3e

Browse files
committedApr 6, 2024·
feat(runtime-vapor): the current instance should be kept in the slot
1 parent db140a1 commit 2e39f3e

File tree

3 files changed

+53
-0
lines changed

3 files changed

+53
-0
lines changed
 

‎packages/runtime-vapor/__tests__/componentSlots.spec.ts

+30
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import {
88
nextTick,
99
ref,
1010
template,
11+
withCtx,
1112
} from '../src'
1213
import { makeRender } from './_utils'
1314

@@ -152,6 +153,35 @@ describe('component: slots', () => {
152153
expect(instance.slots).toHaveProperty('footer')
153154
})
154155

156+
test('the current instance should be kept in the slot', async () => {
157+
let instanceInSlot: any
158+
159+
const Comp = defineComponent({
160+
render() {
161+
const instance = getCurrentInstance()
162+
instance!.slots.default!()
163+
return template('<div></div>')()
164+
},
165+
})
166+
167+
const { instance } = define({
168+
render() {
169+
return createComponent(
170+
Comp,
171+
{},
172+
{
173+
default: withCtx(() => {
174+
instanceInSlot = getCurrentInstance()
175+
return template('content')()
176+
}),
177+
},
178+
)
179+
},
180+
}).render()
181+
182+
expect(instanceInSlot).toBe(instance)
183+
})
184+
155185
test.todo('should respect $stable flag', async () => {
156186
// TODO: $stable flag?
157187
})
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
import {
2+
type ComponentInternalInstance,
3+
currentInstance,
4+
setCurrentInstance,
5+
} from './component'
6+
7+
export function withCtx<T extends (...args: any) => any>(
8+
fn: T,
9+
instance: ComponentInternalInstance | null = currentInstance,
10+
): T {
11+
if (!instance) return fn
12+
13+
const fnWithCtx = ((...args: any[]) => {
14+
const reset = setCurrentInstance(instance)
15+
try {
16+
return fn(...args)
17+
} finally {
18+
reset()
19+
}
20+
}) as T
21+
return fnWithCtx
22+
}

‎packages/runtime-vapor/src/index.ts

+1
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,7 @@ export {
5050
type FunctionalComponent,
5151
type SetupFn,
5252
} from './component'
53+
export { withCtx } from './componentRenderContext'
5354
export { renderEffect } from './renderEffect'
5455
export {
5556
watch,

0 commit comments

Comments
 (0)
Please sign in to comment.