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('用缓存的情况')
    }
  },
相关推荐
世界哪有真情21 分钟前
拿人类意识卡 AI?等于用 bug 验收正式产品
前端·人工智能·后端
鱼樱前端38 分钟前
别再自己拼凑了!这款 Vue 3.5+ 严肃产品级组件库,把 AI 对话、工作流和复杂数据全包了!
javascript·vue.js·github
Listen·Rain1 小时前
Vue3:setup详解
前端·javascript·vue.js
白露与泡影1 小时前
Redis 缓存实战:雪崩、穿透、击穿一次讲透
数据库·redis·缓存
Patrick_Wilson2 小时前
修好 bug 只是开始:一次由监控需求反向重构日志结构的复盘
前端·监控·数据可视化
kyriewen2 小时前
面试官让我优化一个卡死的表格,我打开 Claude 五秒重写,他放下咖啡问我要不要来当组长
前端·javascript·面试
小粉粉hhh3 小时前
React(二)——dom、组件间通信、useEffect
前端·javascript·react.js
Csvn3 小时前
🤖 AI 生成前端代码的 5 个典型翻车现场及修复指南
前端
IT_陈寒4 小时前
SpringBoot自动装配坑了我一天,原来问题出在这
前端·人工智能·后端
索西引擎5 小时前
【React】key 属性:协调算法中的元素标识机制与最佳实践
前端·javascript·react.js