Browse Source

fix(runtime-vapor): current instance is not attached to static slots (#247)

Co-authored-by: 三咲智子 Kevin Deng <sxzz@sxzz.moe>
Rizumu Ayaka 1 year ago
parent
commit
7d90c887c0

+ 34 - 0
packages/runtime-vapor/__tests__/componentSlots.spec.ts

@@ -157,6 +157,40 @@ describe('component: slots', () => {
   })
 
   test('the current instance should be kept in the slot', async () => {
+    let instanceInDefaultSlot: any
+    let instanceInFooSlot: any
+
+    const Comp = defineComponent({
+      render() {
+        const instance = getCurrentInstance()
+        instance!.slots.default!()
+        instance!.slots.foo!()
+        return template('<div></div>')()
+      },
+    })
+
+    const { instance } = define({
+      render() {
+        return createComponent(Comp, {}, [
+          {
+            default: () => {
+              instanceInDefaultSlot = getCurrentInstance()
+              return template('content')()
+            },
+            foo: () => {
+              instanceInFooSlot = getCurrentInstance()
+              return template('content')()
+            },
+          },
+        ])
+      },
+    }).render()
+
+    expect(instanceInDefaultSlot).toBe(instance)
+    expect(instanceInFooSlot).toBe(instance)
+  })
+
+  test('the current instance should be kept in the dynamic slots', async () => {
     let instanceInDefaultSlot: any
     let instanceInVForSlot: any
     let instanceInVIfSlot: any

+ 10 - 5
packages/runtime-vapor/src/componentSlots.ts

@@ -40,12 +40,17 @@ export function initSlots(
   if (!rawSlots) return
   if (!isArray(rawSlots)) rawSlots = [rawSlots]
 
-  if (rawSlots.length === 1 && !isDynamicSlotFn(rawSlots[0])) {
-    instance.slots = rawSlots[0]
+  if (!rawSlots.some(slot => isDynamicSlotFn(slot))) {
+    instance.slots = {}
+    // with ctx
+    const slots = rawSlots[0] as StaticSlots
+    for (const name in slots) {
+      registerSlot(name, slots[name])
+    }
     return
   }
 
-  const resolved: StaticSlots = (instance.slots = shallowReactive({}))
+  instance.slots = shallowReactive({})
   const keys: Set<string>[] = []
   rawSlots.forEach((slots, index) => {
     const isDynamicSlot = isDynamicSlotFn(slots)
@@ -71,7 +76,7 @@ export function initSlots(
               : dynamicSlot && dynamicSlot.name === name)
           ) {
             recordNames.delete(name)
-            delete resolved[name]
+            delete instance.slots[name]
           }
         }
       })
@@ -83,7 +88,7 @@ export function initSlots(
   })
 
   function registerSlot(name: string, fn: Slot, recordNames?: Set<string>) {
-    resolved[name] = withCtx(fn)
+    instance.slots[name] = withCtx(fn)
     recordNames && recordNames.add(name)
   }