1. 程式人生 > 其它 >keep-alive,資料無法重新整理的問題

keep-alive,資料無法重新整理的問題

技術標籤:技術

keep-alive 相關內容

概念:<keep-alive>是Vue的一個內部元件,適合用來快取不需要實時更新的元件,這樣可以保留元件狀態避免重新渲染。

Props:

  • include :接受字串或正則表示式,這裡是需要被快取的元件名
  • exclude :接受字串或正則表示式,這裡是不需要快取的元件名
  • max :接受數字,最多可以快取多少元件例項

問題: 在需要重新請求資料的時候,依然走的快取

案例:

問題描述:
這個專案是一個後臺管理系統,由於很多元件都有走快取的原因,導致在更換賬戶之後,資料依然走的快取,並沒有載入新的資料,從而賬戶雖然已經更換,但是現實的內容還是上一個賬戶下的內容,這時候在network也會發現,除了之前請求的資料,就沒有新資料請求的記錄了

解決方案:

方案1:如果要在進入頁面的時候獲取最新的資料,需要在activated階段獲取資料,承擔原來created鉤子中獲取資料的任務(親測,時而有效,時而無效,不知道是什麼原因)。

方案2:在賬戶登入之後呼叫 **window.location.reload() **,起到重新請求的作用(已親測)

方案3:在vuex中設定狀態,動態繫結 include 值,在登入的時候快取需要快取的元件,在退出的時候,清除需要重新整理的元件(效果很理想,也順帶解決了載入資料時,資料閃現的情況)

//--------------------- VUEX ----------------------------
const state = {
  keepAliveList: 'login,index,productionList,characterList,dynamicList,QAList,fansList'// 需要快取的頁面
}
const mutations = {
  KeepAliveListState (state) {
    state.keepAliveList = 'login,index,productionList,characterList,dynamicList,QAList,fansList'
  },
  removeAliveList (state) {
    state.keepAliveList = 'index'
  }
}
const getters = {
  keepAliveListState (state) {
    return state.keepAliveList
  }
}
export default new Vuex.Store({
  state,
  mutations,
  getters
})

//--------------------- 在app中統一監控----------------
computed: {
    keepAliveList () {
      if (this.$store.getters.keepAliveListState) {
        return this.$store.getters.keepAliveListState
      }
    }
  },
  //--------------------- 在退出的時候,提交removeAliveList ---------------
  this.$store.commit('removeAliveList')
  //--------------------- 在登入的時候,提交KeepAliveListState ---------------
  this.$store.commit('KeepAliveListState')