多个组件使用同一个挂载点,并且进行动态的切换这就是动态组件。
通过使用<component>元素动态的绑定到它的is特性,来实现动态组件
<div id="test">
<button @click="change">切换页面</button>
<component :is="currentView"></component>
</div>
<script> let home = {template:'<div>home</div>'}; let post = {template:'<div>post</div>'}; let end = {template:'<div>end</div>'}; new Vue({ el: '#test', components: { home, post, end }, data:{ index:0, arr:['home','post','end'], }, computed:{ currentView(){ return this.arr[this.index]; } }, methods:{ change(){ this.index = (++this.index)%3; } } }) </script>
使用动态组件来回切换时,组件是要被销毁的,若不想让数据销毁可以使用<keep-alive>,它可以包裹动态组件,这样就不会被销毁。如果多个有条件性的子元素,<keep-alive>要求同时只有一个子元素被渲染。
<div id="test">
<button @click="change">切换页面</button>
<keep-alive>
<component :is="currentView"></component>
</keep-alive>
</div>
当组件在<keep-alive>内切换它的activated和deactivated这两个生命周期钩子函数将会被执行。activated和deactivated这两外钩子函数是专门为<keep-alive>服务的 。
include和exclude属性允许组件有条件地进行缓存,二都都可以用逗号分隔字符串,正则或者是一个数组来表示。
<div id="example">
<button @click="change">切换页面</button>
<keep-alive>
<component :is="currentView" @pass-data="getData"></component>
</keep-alive>
<p>{{msg}}</p>
</div><script>
new Vue({ el: '#example', data:{ index:0, msg:'', arr:[ { template:`<div>我是主页</div>`, activated(){ this.$emit('pass-data','主页被添加'); }, deactivated(){ this.$emit('pass-data','主页被移除'); }, }, {template:`<div>我是提交页</div>`}, {template:`<div>我是存档页</div>`} ], }, computed:{ currentView(){ return this.arr[this.index]; } }, methods:{ change(){ var len = this.arr.length; this.index = (++this.index)% len; }, getData(value){ this.msg = value; setTimeout(()=>{ this.msg = ''; },500) } } }) </script>
<!-- 逗号分隔字符串 -->
<keep-alive include="a,b">
<component :is="view"></component>
</keep-alive>
<!-- 正则表达式 (使用 v-bind) -->
<keep-alive :include="/a|b/">
<component :is="view"></component>
</keep-alive>
<!-- Array (use v-bind) -->
<keep-alive :include="['a', 'b']">
<component :is="view"></component>
</keep-alive>