動態組件允許在同一個掛載點中,根據狀態切換不同組件。常見應用包括頁籤切換、精靈面板、步驟式表單與模組化儀表板。
透過 <component :is="..."> 可以決定要顯示哪個組件。只要變數改變,畫面就會跟著切換。
<div id="app">
<button @click="toggle">切換子組件</button>
<component v-bind:is="currentComponent"></component>
</div>
<script>
new Vue({
el: '#app',
data: {
currentComponent: 'first'
},
methods: {
toggle: function () {
const views = ['first', 'second', 'third', ''];
const index = views.indexOf(this.currentComponent);
this.currentComponent = views[(index + 1) % views.length];
}
},
components: {
first: { template: '<div>子組件一</div>' },
second: { template: '<div>子組件二</div>' },
third: { template: '<div>子組件三</div>' }
}
});
</script>預設情況下,被切換掉的組件會被移除。若希望切回時保留狀態或避免重新渲染,可以在 component 上加入 keep-alive。
<component v-bind:is="currentComponent" keep-alive></component>使用 keep-alive 後,組件會保留在記憶體中,再次顯示時不必重新建立。
如果組件在首次顯示前需要先取得資料,可以使用 activate 鉤子。它適合用於延遲載入、等待 Ajax 完成或初始化非同步資源。
Vue.component('second', {
template: '<div>{{ hello }}</div>',
data: function () {
return {
hello: ''
};
},
activate: function (done) {
const self = this;
fetch('/test')
.then(response => response.text())
.then(data => {
self.hello = data;
done();
});
}
});動態組件切換時,可以搭配過渡效果。若希望動畫更自然,可以設定 transition-mode:
out-in:先離開,再進入。in-out:先進入,再離開。<component
:is="currentComponent"
transition="fade"
transition-mode="out-in">
</component>動態組件的核心在於用狀態控制畫面,再視需求加入快取、延遲載入與過渡效果,讓互動更流暢。