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);
    },

否则会出现滚动加载乱触发的情况。

posted @ 2020-10-23 17:10  巫小婆  阅读(1315)  评论(0编辑  收藏  举报