Vue—keepAlive 动态管理页面缓存

简介

<keep-alive>是Vue的内置组件,当他包裹组件时,会对组件进行缓存,不去销毁组件。

首次进入页面时,会触发mountedactivated钩子,当页面被缓存下来后,进入页面只会触发activated钩子,离开页面会触发deactivated,不会触发destroyed

使用

参数

参数描述
include字符串或正则表达式只有name匹配的组件被缓存
exclude字符串或正则表达式name匹配的组件不会被缓存
// 将缓存 name 为 home 的组件
<keep-alive include='home'>
  <router-view/>
</keep-alive>

// 使用正则表达式
<keep-alive :include='/home|index/'>
  <router-view/>
</keep-alive>

通过路由中的 meta 属性控制

通过在路由中的meta添加keepAlive属性为true,标识当前页面需要进行缓存。

{
      path: '/shop',
      name: 'shop',
      component: () => import('./views/shop.vue'),
      meta: {
        keepAlive: true //此组件需要被缓存
      }
    },

结合v-if进行使用

<keep-alive>
  <router-view v-if="$route.meta.keepAlive" />
</keep-alive>
<router-view v-if="!$route.meta.keepAlive" />

现在我们已经可以缓存页面了,但是在开发过程中,如下场景:

  • list:商品列表页。
  • shop:商品页(被缓存)。
  • order:购买页。

当从列表页跳到商品页时,商品页不需要缓存,只有从购买页跳到商品页时,才需要缓存。

为了满足这种同一个页面有时需要缓存,有时不需要的场景,需要使用路由守卫beforeRouteLeave来实现,根据将要访问的页面判断是否要清除缓存。

beforeRouteLeave(to, from, next) {
    // 回到商品列表不缓存
    if(to.name === 'list'){
      // 清除缓存
      this.$destroy();
    }
    next();
  }
  • 0
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Vue3 的 `keep-alive` 组件提供了动态缓存的功能,可以根据组件的属性值动态缓存组件。 在 Vue2 中,我们可以使用 `include` 和 `exclude` 属性来控制缓存哪些组件和不缓存哪些组件。但是这种方式无法根据组件的属性值进行动态缓存。 在 Vue3 中,我们可以使用 `v-bind` 指令来动态绑定 `keep-alive` 组件的 `include` 和 `exclude` 属性,实现动态缓存的功能。例如: ```html <template> <div> <button @click="toggle">Toggle</button> <keep-alive :include="includeList" :exclude="excludeList"> <router-view /> </keep-alive> </div> </template> <script> export default { data() { return { includeList: [], excludeList: [], show: false, }; }, methods: { toggle() { this.show = !this.show; if (this.show) { this.includeList.push("ComponentA"); this.excludeList = this.excludeList.filter((name) => name !== "ComponentA"); } else { this.excludeList.push("ComponentA"); this.includeList = this.includeList.filter((name) => name !== "ComponentA"); } }, }, }; </script> ``` 在上面的代码中,我们使用 `includeList` 和 `excludeList` 数组来动态控制缓存哪些组件和不缓存哪些组件。在 `toggle` 方法中,根据 `show` 属性的值来决定是否缓存 `ComponentA` 组件。如果 `show` 为 `true`,则将 `ComponentA` 添加到 `includeList` 中,并从 `excludeList` 中删除;如果 `show` 为 `false`,则将 `ComponentA` 添加到 `excludeList` 中,并从 `includeList` 中删除。 这样就可以根据组件的属性值动态缓存组件了。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小白之旅

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值