第一步 在app中設置需要緩存的div
//緩存的頁面
1 <keep-alive> 2 <router-view v-if="$route.meta.keepAlive"></router-view> 3 </keep-alive> 4 5 //不緩存的頁面 6 <router-view v-if="!$route.meta.keepAlive"></router-view>
第二步 在路由router.js中設置.vue頁面是否需要緩存
1 { 2 path: '/', 3 name: 'HomePage', 4 component: HomePage, 5 meta: { 6 keepAlive: false, //此組件不需要被緩存 7 isBack: false, //用於判斷上一個頁面是哪個 8 } 9 }, 10 { 11 path: '/insure', 12 name: 'Insure', 13 component: insure, 14 meta: { 15 keepAlive: true, //此組件需要被緩存 16 isBack:false, //用於判斷上一個頁面是哪個 17 } 18 }, 19 { 20 path: '/confirm', 21 name: 'confirm', 22 component: confirm, 23 meta: { 24 keepAlive: false, //此組件不需要被緩存 25 isBack:false, //用於判斷上一個頁面是哪個 26 } 27 }
第三步
1 beforeRouteEnter(to, from, next) { 2 if (from.name == 'confirm') { 3 to.meta.isBack = true; 4 } 5 next(); 6 }
第四步
當引入keep-alive的時候,頁面第一次進入,鈎子的觸發順序created-> mounted-> activated,退出時觸發deactivated。
當再次進入(前進或者后退)時,只觸發activated。
第五步
默認執行這個方法
1 activated() { 2 if (!this.$route.meta.isBack) { //true執行 3 // 如果isBack是false,表明需要獲取新數據,否則就不再請求,直接使用緩存的數據 4 //清空表單 5 6 } 7 // 恢復成默認的false,避免isBack一直是true,導致下次無法獲取數據 8 this.$route.meta.isBack = false; 9 }
————————————————
版權聲明:本文為CSDN博主「你一定要努力,但千萬別着急」的原創文章,遵循 CC 4.0 BY-SA 版權協議,轉載請附上原文出處鏈接及本聲明。
原文鏈接:https://blog.csdn.net/qq_37330613/article/details/93381094