zoukankan      html  css  js  c++  java
  • 转:vue2.0 keep-alive最佳实践

    转载至:https://segmentfault.com/a/1190000008123035

    1.基本用法

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

    1 <keep-alive>
    2   <component>
    3    <!-- 组件将被缓存 -->
    4   </component>
    5 </keep-alive>

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

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

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

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

    (1)使用router. meta属性
    1 // 这是目前用的比较多的方式
    2 <keep-alive>
    3     <router-view v-if="!$route.meta.notKeepAlive"></router-view>
    4 </keep-alive>
    5 <router-view v-if="$route.meta.notKeepAlive"></router-view>

    router设置

     1 ... 
     2   routes: [
     3     { path: '/', redirect: '/index',  component: Index, meta: { keepAlive: true }},
     4     {
     5       path: '/common',
     6       component: TestParent,
     7       children: [
     8         { path: '/test2', component: Test2, meta: { keepAlive: true } } 
     9       ]
    10     }
    11     ....
    12     // 表示index和test2都使用keep-alive
    (2).使用新增属性inlcude/exclude

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

     1 <!-- comma-delimited string -->
     2 <keep-alive include="a,b">
     3   <component :is="view"></component>
     4 </keep-alive>
     5 <!-- regex (use v-bind) -->
     6 <keep-alive :include="/a|b/">
     7   <component :is="view"></component>
     8 </keep-alive>
     9 
    10 //其中a,b是组件的name

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

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

    includedComponents动态设置即可

  • 相关阅读:
    SQL语句汇总——数据修改、数据查询
    Spring AOP详解
    action类中属性驱动和模型驱动的区别
    数组指针的用法,用处。
    C,C++回文字符串判断(字符串指针的用法)
    C,C++容易被忽略的问题
    c,c++函数返回多个值的方法
    adsf
    Establishing a Build Environmen
    Setting up a Mac OS build environment
  • 原文地址:https://www.cnblogs.com/zhaobao1830/p/7325511.html
Copyright © 2011-2022 走看看