- 動態組件就是幾個組件放在一個掛載點下,然后根據父組件的某個變量來決定顯示哪個,或者都不顯示。
- 在掛載點使用 component 標簽,然后使用 is =“組件名”,它會自動去找匹配的組件名,如果有,則顯示
通過使用保留的 <component>
元素,動態地綁定到它的 is
特性,可以實現動態組件
<div id="example"> <button @click="change">切換頁面</button> <keep-alive> <component :is="currentView"></component> </keep-alive> </div> <script> new Vue({ el: '#example', data:{ index:0, arr:[ {template:`<div>我是主頁</div>`}, {template:`<div>我是提交頁</div>`}, {template:`<div>我是存檔頁</div>`} ], }, computed:{ currentView(){ return this.arr[this.index]; } }, methods:{ change(){ let len = this.arr.length; this.index = (++this.index)% len; } } }) </script>