什么是动态组件
动态组件指的是动态切换组件的显示与隐藏。
如何实现动态组件渲染
- vue 提供了一个内置的 组件,专门用来实现动态组件的渲染
- 默认情况下,切换动态组件时无法保持组件的状态。此时可以使用 vue 内置的 组件保持动态组件的状态。
例如:
<button @click="coms = 'Left'">渲染 Left组件</button>
<button @click="coms = 'Right'">渲染 Right组件</button>
<div class="box">
<!-- 渲染 Left 组件和 Right 组件 -->
<keep-alive>
<component :is="coms"></component>
</keep-alive>
</div>
keep-alive 对应的生命周期函数
- 当组件被缓存时,会自动触发组件的 deactivated 生命周期函数
- 当组件被激活时,会自动触发组件的 activated 生命周期函数。
keep-alive 的 include && exclude 属性
- include 指定相关组件可以形成动态组件
- exclude 和 include 相反
- 若 include || exclude 有多个属性值时,用逗号隔开
<keep-alive include="Left,Right">
<component :is="coms"></component>
</keep-alive>