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('用缓存的情况')
    }
  },
相关推荐
IT_陈寒28 分钟前
Vite的静态资源打包让我熬夜到三点,这坑千万别跳
前端·人工智能·后端
徐小夕1 小时前
万字拆解 JitWord:企业级实时协同文档底层架构 + 大模型 AI 融合完整实践
前端·vue.js·github
一份执念1 小时前
uni-app 小程序分包限制处理与主包体积优化实战
前端·微信小程序
MariaH2 小时前
初识MySQL
前端
陳陈陳2 小时前
从Token到Embedding:一篇文章搞懂大模型的「文字数学变形记」
前端·javascript·ai编程
十有八七2 小时前
AI时代的置身X内
前端·人工智能
小七-七牛开发者2 小时前
TokenPilot:让 LLM Agent 长会话成本降 60%+ 的上下文管理
缓存·agent·token·context·上下文·推理成本
橘子星2 小时前
LLM 无状态架构实践:从原理到代码落地
前端·javascript·人工智能
LiuMingXin2 小时前
意图与代码之间:AI编程范式全景解读
前端·后端·面试
用户83134859306983 小时前
Cesium实现雾气效果:按钮一键控制打开/关闭雾气效果,滑块拖动实时控制雾气浓度
vue.js·cesium