vue使用keep-alive实现页面前进刷新,后退缓存

vue中,我们有时候需要实现这种场景:

1.搜索页面到列表页面,需要刷新重新获取数据。

2.从详情页面返回列表页面需要记住上次浏览的状态。具体流程如下:

效果图

第一步:在路由配置文件中为列表页设置meta参数,里面包含useCatch和keepAlive

javascript 复制代码
{
      path: "/sportPrdtList",
      name: "sportPrdtList",
      component: resolve => require(["@/views/iceArea/sportPrdtList"], resolve),
      meta: {
        keepAlive: true,//是否缓存组件
        useCatch:false//是否用缓存
      }
    },

第二步:在App文件中如下设置

javascript 复制代码
<keep-alive>
<router-view v-if="$route.meta.keepAlive" />
</keep-alive>
<router-view v-if="!$route.meta.keepAlive" />

第三步:在列表页面添加leaveTag字段,当点击返回按钮触发返回事件的时候,将leaveTag修改为back,然后在beforeRouteLeave中如下:

javascript 复制代码
 beforeRouteLeave (to, from, next) {
    if (this.$route.meta && this.$route.meta.keepAlive && this.leaveTag == 'back') {//清空缓存并且将缓存标记(useCatch)置位false
          let vnode = this.$vnode
    let parentVnode = vnode && vnode.parent;
  if (parentVnode && parentVnode.componentInstance && parentVnode.componentInstance.cache) {
    let key = vnode.key == null
      ? vnode.componentOptions.Ctor.cid + (vnode.componentOptions.tag ? `::${vnode.componentOptions.tag}` : '')
      : vnode.key;//获取当前实例的key
    let cache = parentVnode.componentInstance.cache;//获取keep-alive中的缓存对象
    let keys = parentVnode.componentInstance.keys;//获取keep-alive中的key数组
    if (cache[key]) {
      this.$destroy()//销毁当前页面实例
      if (keys.length) {//删除当前页面的key
        let index = keys.indexOf(key)
        if (index > -1) {
            keys.splice(index, 1)
        }
      }
      cache[key] = null//删除当前页面缓存
    }
  }
      this.$route.meta.useCatch = false
    } else {
      if (this.$route.meta && this.$route.meta.keepAlive) {//判断原来是否用到keep-alive
        this.$route.meta.useCatch = true
      } else {//没有缓存直接放行
        return next()
      }
    }
    next()
 },

第四步:在列表页的actived生命周期函数中根据useCatch字段判断是否需要缓存:

javascript 复制代码
 activated () {
    if (!this.$route.meta.useCatch) {
      //不用缓存的情况,首先清除之前缓存的数据然后再获取数据
      console.log('不用缓存的情况', this);
      this.createdMethods()//created生命周期方法
      this.mountedMethods()//mounted生命周期方法
    } else {
      this.$refs.dataList.scrollTop = this.scrollTop//记录页面滚动高度
      console.log('用缓存的情况')
    }
  },
相关推荐
万少3 小时前
小龙虾(openclaw),轻松玩转自动发帖
前端·人工智能·后端
Jagger_5 小时前
抱怨到躺床关灯的一次 DIY 记录
前端
陈随易8 小时前
前端大咖mizchi不满Rust、TypeScript却爱上MoonBit
前端·后端·程序员
whinc9 小时前
🚀 两年小程序开发,我把踩过的坑做成了开源 Skills
前端·微信小程序·ai编程
sure28210 小时前
React Native中创建自定义渐变色
前端·react native
KKKK11 小时前
SSE(Server-Sent Events)流式传输原理和XStream实践
前端·javascript
子兮曰11 小时前
Humanizer-zh 实战:把 AI 初稿改成“能发布”的技术文章
前端·javascript·后端
Din12 小时前
主动取消的防抖
前端·javascript·typescript
百度地图汽车版12 小时前
【AI地图 Tech说】第九期:让智能体拥有记忆——打造千人千面的小度想想
前端·后端
臣妾没空12 小时前
Elpis 全栈框架:从构建到发布的完整实践总结
前端·后端