最近在做一個vue移動端項目,被緩存問題搞得頭都大了,積累了一些經驗,特此記錄總結下,權當是最近項目問題的一個回顧吧!
先描述下問題場景:A頁面->B頁面->C頁面。假設A頁面是列表頁面,B頁面是列表詳情頁面,C頁面是操作改變B頁面的一些東西,進行提交類似的操作。A頁面進入B頁面,應該根據不同的列表item顯示不一樣的詳情,從B進入C,也應該根據item的標識比如ID展示不一樣的內容,在C頁面操作后,返回B頁面,B頁面數據發生變化。這個時候會有兩種情況:
C頁面操作數據后返回B頁面,B頁面對應數據應該發生變化。 C頁面直接點擊左上角箭頭返回,B頁面對應數據不應該發生變化。繼續返回A列表頁面,換一條數據,繼續進入B頁面,B頁面展示不同內容,進入C頁面,C頁面刷新展示不同內容另一種情況發生在寫郵件的頁面中,添加收件人,選人之后,繼續添加,之前添加的聯系人應該存在。但是從寫郵件頁面返回郵件列表再次進入寫郵件頁面,之前添加過的聯系人數據就不應該存在了,這里就涉及到如何處理緩存,何時使用緩存,何時清除緩存的問題了。
目前項目整體結構如下:
<template> <div id="app"> <keep-alive> <router-view v-if="$route.meta.keepAlive"></router-view> </keep-alive> <router-view v-if="!$route.meta.keepAlive"></router-view> </div></template>
雖然官方提供了include,exclude,可以讓我們決定哪些組件使用緩存,哪些不使用緩存,但是并沒有解決我們想動態使用緩存的目的,目前我的項目使用了如下兩種方式處理緩存:
方式一 ,使用是否使用緩存標識
在路由文件router.js里給每個路由添加meta信息,標識是否使用緩存。
meta: {  isUseCache: false,//不使用緩存  keepAlive: true}使用方式:
A->B,B不能緩存;B->A,A緩存。
(1)A頁面:
beforeRouteLeave(to, from, next) { // 設置下一個路由的 meta if(to.path=='/B'){  to.meta.isUseCache = false; } next();},activated(){  if(!this.$route.meta.isUseCache){    this.getData();  }}(2) B頁面
beforeRouteLeave(to, from, next) { // 設置下一個路由的 meta if(to.path=='/A'){  to.meta.isUseCache = true; } next();},activated(){  if(!this.$route.meta.isUseCache){    this.getData();  }} 方式二,強制清除緩存。
這種方式是從網上找的一種方式,使用了vue內部組件之后,不在支持動態銷毀組件,緩存一直存在,只能從源頭上下手,清掉緩存。
export const removeCatch = { beforeRouteLeave:function(to, from, next){  if (from && from.meta.rank && to.meta.rank && from.meta.rank>to.meta.rank)   {//此處判斷是如果返回上一層,你可以根據自己的業務更改此處的判斷邏輯,酌情決定是否摧毀本層緩存。     if (this.$vnode && this.$vnode.data.keepAlive)     {       if (this.$vnode.parent && this.$vnode.parent.componentInstance && this.$vnode.parent.componentInstance.cache)       {         if (this.$vnode.componentOptions)         {           var key = this.$vnode.key == null                 ? this.$vnode.componentOptions.Ctor.cid + (this.$vnode.componentOptions.tag ? `::${this.$vnode.componentOptions.tag}` : '')                 : this.$vnode.key;           var cache = this.$vnode.parent.componentInstance.cache;           var keys = this.$vnode.parent.componentInstance.keys;           if (cache[key])           {             if (keys.length) {               var index = keys.indexOf(key);               if (index > -1) {                 keys.splice(index, 1);               }             }             delete cache[key];           }         }       }     }     this.$destroy();   }   next(); }};            
新聞熱點
疑難解答
圖片精選