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('用缓存的情况')
    }
  },
相关推荐
李姆斯38 分钟前
管理是否可以被完全量化
前端·产品经理·团队管理
名字还没想好☜1 小时前
Next.js 中间件实战:鉴权、重定向与 A/B 分流
开发语言·前端·javascript·中间件·react·next.js
广州灵眸科技有限公司2 小时前
瑞芯微RV1126B开发板(EASY-EAI-PI2) INI文件操作
java·前端·javascript·网络·人工智能
江华森2 小时前
Web 开发基础:HTTP 与 REST
前端·网络协议·http
IT_陈寒3 小时前
Redis的KEYS命令把我搞崩溃了,改用SCAN才活过来
前端·人工智能·后端
Jackson__3 小时前
为什么 Agent 越聊越慢?聊聊 Context(上下文)管理
前端·agent·ai编程
KaMeidebaby3 小时前
卡梅德生物技术快报|抗体合成:多肽抗体合成工程化方案:Nsp2 保守肽多抗制备与多维度验证
前端·网络·数据库·人工智能·算法
青禾网络4 小时前
前端做音画匹配这件事,我从"随机塞"到"AI 自动对齐"
前端·github
2601_963771374 小时前
Hardening Enterprise WordPress Sites Against REST API Leaks and Bad Headers
前端·windows·word·php
蓝银草同学4 小时前
Stream 实战:博客列表排序、过滤与分页(AI 辅助学习 Java 8)
java·前端·后端