vue中的keep-alive

官方文档:

keep-alive

如果把切换出去的组件保留在内存中,可以保留它的状态或避免重新渲染。为此可以添加一个 keep-alive 指令参数:

<keep-alive>
  <component :is="currentView">
    <!-- 非活动组件将被缓存! -->
  </component>
</keep-alive>
  • Props:

    • include - 字符串或正则表达式。只有匹配的组件会被缓存。
    • exclude - 字符串或正则表达式。任何匹配的组件都不会被缓存。
  • 用法:

    <keep-alive> 包裹动态组件时,会缓存不活动的组件实例,而不是销毁它们。和 <transition> 相似,<keep-alive> 是一个抽象组件:它自身不会渲染一个 DOM 元素,也不会出现在父组件链中。

    当组件在 <keep-alive> 内被切换,它的 activated 和 deactivated 这两个生命周期钩子函数将会被对应执行。

    在 2.2.0 及其更高版本中,activated 和 deactivated 将会在 <keep-alive> 树内的所有嵌套组件中触发。

2.1.0 新增:include 和 exclude 属性允许组件有条件地缓存。二者都可以用逗号分隔字符串、正则表达式或一个数组来表示:

<!-- 逗号分隔字符串 -->
<keep-alive include="a,b">
  <component :is="view"></component>
</keep-alive>

<!-- 正则表达式 (使用 `v-bind`) -->
<keep-alive :include="/a|b/">
  <component :is="view"></component>
</keep-alive>

<!-- 数组 (使用 `v-bind`) -->
<keep-alive :include="['a', 'b']">
  <component :is="view"></component>
</keep-alive>

匹配首先检查组件自身的 name 选项,如果 name 选项不可用,则匹配它的局部注册名称 (父组件 components 选项的键值)。匿名组件不能被匹配。

<keep-alive> 不会在函数式组件中正常工作,因为它们没有缓存实例。

动态判断
<keep-alive :include="includedComponents">
  <router-view></router-view>
</keep-alive>

includedComponents动态设置即可

在2.1.0之前,我们可以这样做:

缓存部分页面或者组件
(1)使用router.mate属性
// 这是目前用的比较多的方式
<keep-alive>
    <router-view v-if="!$route.meta.notKeepAlive"></router-view>
</keep-alive>
<router-view v-if="$route.meta.notKeepAlive"></router-view>
router设置
 routes: [
    { path: '/', redirect: '/index',  component: Index, mate: { keepAlive: true }},
    {
      path: '/common',
      component: TestParent,
      children: [
        { path: '/test2', component: Test2, mate: { keepAlive: true } } 
      ]
    }
// 表示index和test2都使用keep-alive

参考链接:http://www.jianshu.com/p/e4bd12e789dd

转载于:https://www.cnblogs.com/fanlinqiang/p/8028669.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值