Преглед изворни кода

refactor(vapor): use context pattern to control scope retention (#14305)

edison пре 3 месеци
родитељ
комит
bf0db00244

+ 4 - 5
packages/runtime-vapor/src/components/KeepAlive.ts

@@ -229,14 +229,13 @@ const KeepAliveImpl: ObjectVaporComponent = defineVaporComponent({
     // inject hooks to DynamicFragment to cache components during updates
     const injectKeepAliveHooks = (frag: DynamicFragment) => {
       ;(frag.onBeforeTeardown || (frag.onBeforeTeardown = [])).push(
-        (oldKey, nodes, scope) => {
+        (oldKey, { retainScope }) => {
           // if the fragment's nodes include a component that should be cached
-          // return true to avoid tearing down the fragment's scope
+          // call retainScope() to avoid stopping the fragment's scope
           if (processFragment(frag)) {
-            keptAliveScopes.set(oldKey, scope)
-            return true
+            keptAliveScopes.set(oldKey, frag.scope!)
+            retainScope()
           }
-          return false
         },
       )
       ;(frag.onBeforeMount || (frag.onBeforeMount = [])).push(() =>

+ 8 - 10
packages/runtime-vapor/src/fragment.ts

@@ -93,9 +93,8 @@ export class DynamicFragment extends VaporFragment {
   // hooks
   onBeforeTeardown?: ((
     oldKey: any,
-    nodes: Block,
-    scope: EffectScope,
-  ) => boolean)[]
+    context: { retainScope: () => void },
+  ) => void)[]
   onBeforeMount?: ((newKey: any, nodes: Block, scope: EffectScope) => void)[]
 
   slotOwner: VaporComponentInstance | null
@@ -137,17 +136,16 @@ export class DynamicFragment extends VaporFragment {
     const parent = isHydrating ? null : this.anchor.parentNode
     // teardown previous branch
     if (this.scope) {
-      let preserveScope = false
-      // if any of the hooks returns true the scope will be preserved
-      // for kept-alive component
+      let retainScope = false
+      const context = {
+        retainScope: () => (retainScope = true),
+      }
       if (this.onBeforeTeardown) {
         for (const teardown of this.onBeforeTeardown) {
-          if (teardown(prevKey, this.nodes, this.scope!)) {
-            preserveScope = true
-          }
+          teardown(prevKey, context)
         }
       }
-      if (!preserveScope) {
+      if (!retainScope) {
         this.scope.stop()
       }
       const mode = transition && transition.mode