vue之keep-alive加深印象

451 阅读1分钟

定义:

包裹动态组件时,会缓存不活动的组件实例,而不是销毁它们

生命周期:

activated:当 keepalive 包含的组件再次渲染的时候触发

deactivated: 当 keepalive 包含的组件销毁的时候触发

参数

include 包含的组件(可以为字符串,数组,以及正则表达式,只有匹配的组件会被缓存)

exclude 排除的组件(以为字符串,数组,以及正则表达式,任何匹配的组件都不会被缓存)

max 缓存组件的最大值(类型为字符或者数字,可以控制缓存组件的个数)

//缓存name名称为list和table的组件
<keep-alive include="list,table">
  <component></component>
</keep-alive>
​
​
//不缓存name名称为list和table的组件
<keep-alive exclude="list,table">
  <component></component>
</keep-alive><!-- 如果同时使用include,exclude,那么exclude优先于include, 下面的例子只缓存a组件 -->
<keep-alive include="list,exclude" exclude="exclude"> 
  <component></component>
</keep-alive>
​
​
<!-- 如果缓存的组件超过了max设定的值10,那么将删除第一个缓存的组件 -->
<keep-alive  max="10"> 
  <component></component>
</keep-alive><keep-alive include="table">
    <router-view>
        <!-- 只有路径匹配到的 include 为 table 组件会被缓存 -->
    </router-view>
</keep-alive>
<!--index.vue -->
<keep-alive>
    <router-view v-if="$route.meta.keepAlive"></router-view>
</keep-alive>
<router-view v-if="!$route.meta.keepAlive"></router-view>
​
//...router.js
export default new Router({
  routes: [
    {
      path: '/list',
      name: 'list',
      component: list,
      meta: {
        keepAlive: false // 不需要缓存
      }
    },
    {
      path: '/table',
      name: 'table',
      component: table,
      meta: {
        keepAlive: true // 需要被缓存
      }
    }
  ]
})
​
​