vue2.0 keep-alive最佳实践

1.基本用法

vue2.0提供了一个keep-alive组件用来缓存组件,避免多次加载相应的组件,减少性能消耗

<keep-alive>
<component>
  <!-- 组件将被缓存 -->
</component>
</keep-alive>

有时候 可能需要缓存整个站点的所有页面,而页面一般一进去都要触发请求的
在使用keep-alive的情况下

<keep-alive><router-view></router-view></keep-alive>

将首次触发请求写在created钩子函数中,就能实现缓存,比如列表页,去了详情页 回来,还是在原来的页面

2.缓存部分页面或者组件

(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
(2).使用新增属性inlcude/exclude

2.1.0后提供了include/exclude两个属性 可以针对性缓存相应的组件

<!-- comma-delimited string -->
<keep-alive include="a,b">
  <component :is="view"></component>
</keep-alive>
<!-- regex (use v-bind) -->
<keep-alive :include="/a|b/">
  <component :is="view"></component>
</keep-alive>

//其中a,b是组件的name

注意:这种方法都是预先知道组件的名称的

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

includedComponents动态设置即可

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,962评论 19 139
  • keep-alive用法 <keep-alive> 包裹动态组件时,会缓存不活动的组件实例,而不是销毁它们。和 ...
    MrLhx阅读 1,549评论 0 2
  • vue 2.0 渐进式框架 MVC 单向通信 > m:model 数据层 保存数据 > v:view视图层 用户界...
    web前端ling阅读 756评论 0 0
  • 这篇笔记主要包含 Vue 2 不同于 Vue 1 或者特有的内容,还有我对于 Vue 1.0 印象不深的内容。关于...
    云之外阅读 5,079评论 0 29
  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 173,405评论 25 708