keep-alive 单页面前进刷新、后退缓存

本文探讨了如何利用Vue的keep-alive组件实现在单页面应用中前进刷新、后退缓存的效果。详细解析了不同情况下钩子函数的执行顺序,并提供了两种记录页面滚动高度的方案:一种是通过ref和activated钩子恢复高度,另一种是在router配置中全局处理。这两种方案都旨在优化用户体验。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

注意: 暂未考虑用户手动刷新整个页面及多次replace跳转情况。

这种方案虽然能实现前进刷新后退缓存的效果,但仅仅只是简单实现。github有类似更好的方案,后续再补…

B为预期缓存页面: A->B->C时,A前进至B,B不缓存,若A->B->C->B,此时C后退到B,B缓存

理解钩子函数的执行顺序

  • 不使用keep-alive
    beforeRouteEnter --> created --> mounted --> destroyed;

  • 使用keep-alive
    beforeRouteEnter --> created --> mounted --> activated --> deactivated;
    再次进入缓存的页面,只会触发beforeRouteEnter -->activated --> deactivated ;

// 1. 修改app.vue  
<keep-alive>
  <router-view v-if="$route.meta.keepAlive" :key="$route.fullPath"></router-view>
</keep-alive>
<router-view v-if="!$route.meta.keepAlive" :key="$route.fullPath"></router-view>
// 除了v-if  也可以使用include参数实现

// 2. 修改路由 router/index.ts, 添加meta.keepAlive 需要缓存的页面设为True
{
  path: '/all-Application',
  name: 'AllApplication',
  component: () => import('xxx'),
  meta: {
    keepAlive: true,
  },
},

// 3. 定义全局变量 routerList用于记录路由跳转,keepAlived 记录需要缓存的路由name
const routerList: any = [];
const keepAlived = [
  'MyInitiate',
  'Draft',
  'Upcoming',
  'MyProcess',
  'AllApplication',
  'AllApplicationForms',
];
// 4. 配置全局路由守卫router.beforeEach
router.beforeEach(async (to, from, next) => {
  alive(to, from);
  next();
}

const alive = (to: Route, from: Route) => {
  const li = routerList.length;

  /* 含 replace 后退 */
  const isGoback =
    (li > 1 && routerList[li - 2] === to.name) || (li > 0 && routerList[li - 1] === to.name);

  if (isGoback) {
    const isKeepAliveComponent = keepAlived.includes(to.name ?? '');

    to.meta.keepAlive = isKeepAliveComponent;
    from.meta.keepAlive = false;

    routerList.splice(routerList.length - 1, 1);
  } else {
    if (from.name) {
      const isKeepAliveComponent = keepAlived.includes(from.name);

      to.meta.keepAlive = false;
      from.meta.keepAlive = isKeepAliveComponent;

      /* replace 时也会 push */
      routerList.push(from.name);
    }
  }
};

5.记录页面滚动高度
方案一:

  • 5.1 给滚动元素绑定 ref
  • 5.2 定义变量:记录滚动高度
private scroll: number = 0;
  • 5.3 离开页面时记录当前高度
this.scroll = (this.$refs.tabScroll as HTMLElement).scrollTop;
  • 5.4 添加activated钩子 再次进入时恢复页面高度
private activated() {
  (this.$refs.tabScroll as HTMLElement).scrollTop = this.scroll;
}

页面缓存 变量的值不会改,所以这里没有使用vuex来存滚动高度,当页面是由别的页面前进 进入的,那么会刷新,高度会自动重置为默认值0;

方案二:
router/index.js中添加如下代码(推荐)

mode: 'history',
scrollBehavior(to, from, savedPosition) {
    if (savedPosition) {
        return savedPosition
    } else {
        return {
            x: 0,
            y: 0
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值