使用场景:
不常用的组件可以用其包裹缓存,减少DOM渲染,影响性能;
一般使用在动态渲染组件上;
// 使用keep-alive组件缓存切换组件之前的状态和内容,避免dom多次渲染
<div id="app">
<button @click="switchComp('child1')">组件1</button>
<button @click="switchComp('child2')">组件2</button>
<keep-alive>
<component :is="chooseComponent"></component> // 需要切换的动态组件;
</keep-alive>
</div>
未使用keep-alive:
使用keep-alive包裹缓存情况:
属性:
include- 字符串或正则表达式。只有名称匹配的组件会被缓存。exclude- 字符串或正则表达式。任何名称匹配的组件都不会被缓存。max- 数字。最多可以缓存多少组件实例。
<!-- 逗号分隔字符串 -->
<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>
<keep-alive :max="10">
<component :is="view"></component>
</keep-alive>