動態組件適合在同一個區域中切換不同畫面或模組。與撰寫多個獨立頁面相比,動態組件能讓狀態管理與畫面切換更集中。
透過 <component :is="...">,可以依變數決定目前要顯示的組件。
<component v-bind:is="currentView"></component>當 currentView 改變時,Vue.js 會自動切換對應組件。如果找不到符合的組件,則不會顯示內容。
若切換後希望組件不要立即銷毀,可以加上 keep-alive。這適合表單草稿、多步驟流程或需要保留捲動位置的場景。
<component v-bind:is="currentView" keep-alive></component>當組件第一次顯示前需要非同步資料時,可以使用 activate。它會延遲組件切換,直到指定工作完成。
Vue.component('async-view', {
template: '<div>{{ content }}</div>',
data: function () {
return {
content: ''
};
},
activate: function (done) {
fetch('/api/data')
.then(response => response.text())
.then(text => {
this.content = text;
done();
});
}
});動態組件切換時可以加入動畫。若希望先讓舊畫面離開,再讓新畫面進入,可使用 transition-mode="out-in"。
<component
:is="currentView"
transition="fade"
transition-mode="out-in">
</component>動態組件的重點在於:用狀態控制畫面、用 keep-alive 管理快取、用 activate 處理延遲載入,並用過渡模式提升切換體驗。