此博客是本人从学生时代开始做笔记所用, 部分是工作所遇问题,做填坑笔记,部分闲来查阅资料,加上自己的理解所总结的学习笔记, 常忙得不可开交,若漏了资料来源,望通知~ 前路漫漫,写点东西告诉自己正在一点点进步,而不要迷失于繁忙。

keep-alive使用笔记

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

1.将整个网页缓存起来

<router-view 
    class="view"  
    keep-alive  
    transition  
    transition-mode="out-in">  
  </router-view>

最常用的方式,用以提高整体的加载速度。

 

2.缓存部分组件或页面

a.使用include与exclude

<keep-alive include="a,b"> <!--缓存name为a或b的组件-->
  <component :is="view"></component>
</keep-alive>
<!-- regex (use v-bind) -->
<keep-alive :include="/a|b/"> <!--缓存name正则匹配/a|b/的组件-->
 <component :is="view"></component> </keep-alive>

官网推荐的方法

 

b.使用router.mate

// 这是目前用的比较多的方式
<keep-alive>
    <router-view v-if="$route.mate.keepAlive"></router-view>
</keep-alive>
<router-view v-if="!$route.mate.keepAlive"></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

根据router设置中的mate值来判断是否加载此组件

posted @ 2017-10-10 15:04  炎泽  阅读(515)  评论(0编辑  收藏  举报