app嵌入h5缓存界面,清除缓存界面代码

界面需要缓存常用场景:
商城主界面home.vue进入商品列表界面productList.vue,
点击商品查看详情需要给商品列表界面缓存,
若不缓存,从商品详情界面返回到商品列表界面会重新刷新商品列表数据,滚动位置就会被清除

  1. 路由配置界面需要缓存
{
   path: '/home',
   name: 'home',
   component: () => import('@/views/home.vue')
}, {
   path: '/productList',
   name: 'productList',
   component: () => import('@/views/productList.vue'),
   meta: {
     keepAlive: true // 需要被缓存
   }
}, {
   path: '/productDetail',
   name: 'productDetail',
   component: () => import('@/views/productDetail.vue')
}
  1. app.vue中使用keep-alive标签缓存界面
<keep-alive>
  <router-view
    v-if="$route.meta.keepAlive"
    :key="$route.fullPath"
  ></router-view>
</keep-alive>
<router-view
  v-if="!$route.meta.keepAlive"
  :key="$route.fullPath"
></router-view>
  1. 清除缓存
    商品列表进入详情会自动缓存,
    但从商品列表返回到主页时需要清除缓存
beforeRouteLeave(to, from, next) { // 返回上一页清除缓存
  if (to.path === '/home') {
    let that = this
    if (that.$vnode && that.$vnode.data.keepAlive) {
      if (that.$vnode.parent && that.$vnode.parent.componentInstance && that.$vnode.parent.componentInstance.cache) {
        if (that.$vnode.componentOptions) {
          var key = that.$vnode.key == null
              ? that.$vnode.componentOptions.Ctor.cid + (that.$vnode.componentOptions.tag ? `::${that.$vnode.componentOptions.tag}` : '')
              : that.$vnode.key
          var cache = that.$vnode.parent.componentInstance.cache
          var keys = that.$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]
          }
        }
      }
    }
    that.$destroy()
  }
  next()
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值