組件是 Vue.js 中可重複使用的介面單元。它能封裝模板、資料與行為,讓複雜頁面可以拆成多個可維護的小單元。
可以透過 Vue.component 全域註冊,也可以在父組件的 components 選項中局部註冊。
Vue.component('my-component', {
template: '<div>這是一個組件</div>'
});const Child = Vue.extend({
template: '<div>子組件</div>'
});
const Parent = Vue.extend({
components: {
'my-component': Child
}
});組件作用域預設是獨立的,父組件若要把資料傳給子組件,應透過 props。
Vue.component('child', {
props: ['msg'],
template: '<span>{{ msg }}</span>'
});<child msg="hello"></child>若要傳遞動態表達式,可使用 v-bind:
<child :msg="parentMessage"></child>子組件可以透過事件通知父組件。做法是子組件觸發自訂事件,父組件使用 v-on 監聽。
<child v-on:child-msg="handleMessage"></child>Vue.component('child', {
template: '<button v-on:click="notify">送出訊息</button>',
methods: {
notify: function () {
this.$emit('child-msg', '來自子組件的訊息');
}
}
});Slot 允許父組件把內容插入子組件模板中。
<my-component>
<p>這段內容會被插入子組件</p>
</my-component>子組件模板:
template: '<div><slot></slot></div>'使用 <component :is="..."> 可以在多個組件之間切換。
<component :is="currentView"></component>若希望切換後保留狀態,可加上 keep-alive:
<component :is="currentView" keep-alive></component>大型應用可以把組件延後載入。Vue.js 允許把組件定義為工廠函數。
Vue.component('async-example', function (resolve) {
setTimeout(function () {
resolve({
template: '<div>異步組件</div>'
});
}, 1000);
});組件可以在自己的模板中引用自己,但需要 name 與終止條件。
const StackOverflow = Vue.extend({
name: 'stack-overflow',
template: '<div><stack-overflow v-if="condition"></stack-overflow></div>'
});如果模板有多個根節點、只有文字,或根節點帶有流程控制指令,可能形成片斷實例。實務上建議讓組件模板保持單一根節點,以確保屬性、事件與過渡能正確作用。
Vue.js 組件的強大之處在於:props 負責輸入資料、事件負責對外通知、slot 負責內容組合。掌握這三者,就能建立清楚且可重用的元件架構。