自学内容网 自学内容网

vue2+keep-alive h5端 从首页进入客户列表-客户列表更新,从客户列表进入客户详情再返回,客户列表需要缓存筛选条件以及滚动位置

确保 路由层级是2级

在app.vue 添加如下代码

<keep-alive :include="include">
      <!--带 keepAlive 的标识页面进行缓存 从详情列表再进来会更新或者自己手动更新-->
     <router-view v-if="$route.meta.keepAlive "></router-view>
 </keep-alive>

<router-view v-if="!$route.meta.keepAlive "/>

include: []


watch: {
    $route(to, from) {
      //如果 要 to(进入) 的页面是需要 keepAlive 缓存的,把 name push 进 include数组
      if (to.meta.keepAlive) {
        !this.include.includes(to.name) && this.include.push(to.name);
      }
      //如果 要 form(离开) 的页面是 keepAlive缓存的,
      //再根据 deepth 来判断是前进还是后退
      //如果是后退
     
      if (from.meta.keepAlive && to.meta.deepth < from.meta.deepth) {
        var index = this.include.indexOf(from.name);
        index !== -1 && this.include.splice(index, 1);
      }
    }
  },

路由设置 要点
+ 需要缓存的地方添加 keepAlive:true , deepth: 1
+ 从列表回到首页的时候 需要列表设置deepth: 1 首页设置deepth 0.5 ,确保列表大于首页

对应二级路由写法

{
    path: '/businessChance/list',
    name: 'businessChanceList',
    component: resolve => require(['@qwH5Views/businessChance/page/index.vue'], resolve),
    meta: { hideFoot: true, title: '商机管理', code: '51100001', keepAlive:true , deepth: 1  }
},
{
   path: '/business/createbusiness',
   name: 'createBusiness',
   component: resolve => require(['@qwH5Views/business/page/createBusiness.vue'], resolve),
   meta: { hideFoot: true, title: '新建商机', }
 },

{
    path: '/home/index',
    name: 'homeIndex',
    meta: { title: '首页' ,deepth: 0.1},
    component: resolve => require(['@qwH5Views/home/page/newHome/index.vue'], resolve)
  },

记住 路由里面设置的name 跟 自己页面里面name 要对应

恢复滚动条方法

 @scroll="handleScrollList"
 
 handleScrollList(){
      // 当前页面滚动位置
      sessionStorage.setItem('loadContPage', this.$refs.loadContPage.scrollTop)
    },

async activated() {
    console.log('子组件的activated');  
    // 让滚动条复原
    this.$refs.loadContPage.scrollTo(0, sessionStorage.getItem('loadContPage'))
  },
    ```

原文地址:https://blog.csdn.net/csstmg/article/details/142549105

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!