Эх сурвалжийг харах

keep-alive 增加逻辑的注释

Michael Wang 4 жил өмнө
parent
commit
77eebdaeac
1 өөрчлөгдсөн 16 нэмэгдсэн , 8 устгасан
  1. 16 8
      src/mixins/keepAlive.js

+ 16 - 8
src/mixins/keepAlive.js

@@ -1,12 +1,14 @@
 import { keepAliveRoutesPairs } from "@/constant/constants";
 import Vue from "vue";
 
+// keepAliveRoutesPairs = [ [A, [B, C]], [D, [B]]] // mainRoute secondaryRoute
 Vue.mixin({
   beforeRouteEnter(to, from, next) {
     next((vm) => {
-      const tos = keepAliveRoutesPairs.map((v) => v[0]);
+      const mainRoutes = keepAliveRoutesPairs.map((v) => v[0]);
       if (
-        tos.includes(to.name) &&
+        // 当进入 A 时,将 A 缓存
+        mainRoutes.includes(to.name) &&
         vm.$store.state.keepAliveRoutes.length === 0
       ) {
         vm.$store.commit("setRestoreKeepAliveRoutes");
@@ -14,18 +16,24 @@ Vue.mixin({
     });
   },
   beforeRouteLeave(to, from, next) {
-    console.log(from.name, to.name);
-    const froms = keepAliveRoutesPairs.map((v) => v[0]);
+    const mainRoutes = keepAliveRoutesPairs.map((v) => v[0]);
     if (
-      (froms.includes(from.name) &&
-        keepAliveRoutesPairs[froms.indexOf(from.name)][1].includes(to.name)) ||
-      (froms.includes(to.name) &&
-        keepAliveRoutesPairs[froms.indexOf(to.name)][1].includes(from.name))
+      // 当离开 A 到 [B, C] 时,确保 A 缓存了
+      (mainRoutes.includes(from.name) &&
+        keepAliveRoutesPairs[mainRoutes.indexOf(from.name)][1].includes(
+          to.name
+        )) ||
+      // 当 [B, C] 回到 A 时,确保 A 缓存了
+      (mainRoutes.includes(to.name) &&
+        keepAliveRoutesPairs[mainRoutes.indexOf(to.name)][1].includes(
+          from.name
+        ))
     ) {
       // 减少无谓的commit
       if (this.$store.state.keepAliveRoutes.length === 0)
         this.$store.commit("setRestoreKeepAliveRoutes");
     } else {
+      // 其他情况的 leave 都清空缓存。至于在下个页面是否缓存,交给 beforeRouteEnter 判断
       if (this.$store.state.keepAliveRoutes.length > 0)
         this.$store.commit("setEmptyKeepAliveRoutes");
     }