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('用缓存的情况')
    }
  },
相关推荐
碎_浪36 分钟前
给键盘党的英语记忆工具:我做了一款「打字背单词」桌面应用
前端·程序员·ai编程
阿成学长_Cain2 小时前
Linux dirs命令详解|Bash目录堆栈管理快速切换目录实战教程
linux·运维·前端·数据库
yqcoder2 小时前
httpOnly 是什么,又有什么用?
开发语言·前端·javascript
IT_陈寒2 小时前
Java的Stream.parallel()把我CPU跑爆了,这种优化要谨慎
前端·人工智能·后端
小皮虾2 小时前
小程序首页性能优化实战:从 4 秒到 1.8 秒
前端·微信小程序
山河木马3 小时前
GPU自动处理专题1-裁剪到底在裁什么(裁剪)
前端·webgl·计算机图形学
奔跑的蜗牛ing3 小时前
CentOS Nginx 安装与静态文件服务器配置指南
前端·面试·架构
子兮曰3 小时前
Bun 重写为 Rust:11天、64个Claude、16.5万美元,一次改变行业认知的激进实验
前端·后端·bun
子兮曰3 小时前
Node.js v26.5.0 深度解读:import Text、流式 ReadableStreamTee、以及隐藏的安全加固浪潮
前端·后端·node.js