vue-router keepalive 頁面緩存的實現(詳情返回列表並記錄列表頁狀態)


實現場景:

當前頁面有不同的狀態切換,並且有相應的列表值。比如:淘寶的訂單列表頁面的布局方式。有已發貨,待發貨,已收貨,全部訂單等。當點擊已發貨下的訂單列表時,可以跳轉到訂單詳情頁面。當點擊返回的時候,返回到已發貨/待發貨狀態下相應的列表位置。並且頁面不會發送請求。

實現原理:

官方文檔指路

kee-alive 是 Vue 內置的一個組件,可以使被包含的組件保留狀態,或避免重新渲染

實現方式:

1,APP.vue

<template>
  <div id="app" class="mescroll-touch" v-cloak>
    <keep-alive :include="include">
      <!--  v-if="!$route.meta.keepAlive" -->
      <router-view></router-view>
    </keep-alive>
    <!-- <router-view v-if="!$route.meta.keepAlive"></router-view> -->
  </div>
</template>

在data里定義一個字段 include:[],並且在watch里監聽$route

 watch: {
      $route(to, from) {
        // 如果要to(進入)的頁面是需要keepAlive緩存的,把name push進include數組中
        if (from.meta&&to.meta&&from.meta.deepth&&to.meta.keepAlive) {
          !this.include.includes(to.name) && this.include.push(to.name);
        }
        // 如果 要 form(離開) 的頁面是 keepAlive緩存的,
        // 再根據 deepth 來判斷是前進還是后退
        // 如果是后退:
        if (from.meta&&to.meta&&from.meta.keepAlive && to.meta.deepth < from.meta.deepth) {
          const index = this.include.indexOf(from.name);
          index !== -1 && this.include.splice(index, 1);
        }
        // 如果回到了首頁,那么緩存為空
        if(to.meta.deepth==1){
          this.include=[]
        }
      }
  },

2,配置路由屬性,在router里的index.js 里定義屬性meta: { title: 'xxx',keepAlive:true,deepth:5},這里注意name 值要跟頁面組件里的name值保持一致,否則無效。關於

deepth的值 首頁 < 列表 < 詳情 這樣可以做到前進后退 區分要緩存哪一頁。
 {
            name:'couponIndex',
            path:'/couponIndex',
            component: routerData.router.coupon_index,
            meta: { title: '卡券',deepth:4}
        },
        {
            name:'couponInfo',
            path:'/couponInfo',
            component: routerData.router.coupon_info,
            meta: { title: '卡券詳情',keepAlive:true,deepth:6}
        },
        {
            name:'couponList',
            path:'/couponList',
            component: routerData.router.coupon_list,
            meta: { title: '我的卡包',keepAlive:true,deepth:5}
        },

3,在 couponList.vue 里 定義name: "couponList;couponInfo.vue 里定義 name: "couponInfo"。在meta里定義keeplive:true 的頁面里分別定義name值即可。

 4,如果要緩存的頁面里存在滾動事件監聽,比如上拉加載更多的時候,滾動監聽方法的觸發和移除 放在activated和deactivated兩個生命周期中。

activated(){
        window.addEventListener('scroll', this.initHeight);
    },
     //離開刪除綁定事件
    deactivated() {
        window.removeEventListener("scroll",this.initHeight);
    },

否則會出現滾動加載亂觸發的情況。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM