什麼是組件
組件(component)是 Vue.js 的核心概念之一。它可以擴充 HTML 元素、封裝可重複使用的程式碼;從較高的層次來看,組件就是自定義元素,Vue.js 的編譯器會為它加上特殊能力。在某些情境下,組件也能以原生 HTML 元素的形式出現,透過 is 屬性來擴展。
可以把 Vue.js 的組件理解為「預先定義好行為的 ViewModel 類」。一個組件能宣告許多選項,其中最核心的有六項:
模板(template):聲明資料與最終呈現給使用者的 DOM 之間的映射關係。
初始資料(data):組件的初始狀態。對可重複使用的組件而言,這通常是私有狀態。
外部參數(props):組件之間透過參數傳遞與共享資料。預設為單向綁定(由上而下),也可以顯式宣告為雙向綁定。
方法(methods):對資料的改動通常都在方法內進行,並透過 v-on 將使用者輸入事件與方法綁定。
生命週期鉤子(lifecycle hooks):組件會觸發 created、attached、destroyed 等多個鉤子。相較於傳統 MVC,可以理解為 Controller 的邏輯被分散到這些時機點上。
私有資源(assets):Vue.js 把自定義的指令、過濾器、組件統稱為資源。由於全域註冊容易導致命名衝突,組件可以宣告自己的私有資源,僅供自身與子組件使用。
除此之外,同一棵組件樹內的組件之間還能透過內建的事件 API 溝通。Vue.js 提供了完善的定義、複用與嵌套機制,讓開發者能像堆積木一樣組出整個介面,大幅提升了程式碼的複用率與可維護性。
註冊組件的三個步驟
1. 建立組件構造器:
var MyComponent = Vue.extend({
// 選項
})
2. 用 Vue.component 註冊:
Vue.component('my-component', MyComponent)
3. 在父實例中以自定義元素形式使用:
<div id="example"> <my-component></my-component> </div>
完整例子:
<div id="example">
<my-component></my-component>
</div>
// 定義
var MyComponent = Vue.extend({
template: '<div>A custom component!</div>'
})
// 註冊
Vue.component('my-component', MyComponent)
// 建立根實例
new Vue({ el: '#example' })
渲染結果:
<div id="example"> <div>A custom component!</div> </div>
組件的模板取代了自定義元素,自定義元素的作用僅作為掛載點。可以用實例選項 replace 決定是否替換。
局部註冊
用實例選項 components 註冊,可以讓組件只在特定範圍內可用,避免全域註冊每一個組件:
var Child = Vue.extend({ /* ... */ })
var Parent = Vue.extend({
template: '...',
components: {
// <my-component> 只能用在父組件模板內
'my-component': Child
}
})
這種封裝方式同樣適用於指令、過濾器與過渡效果。
data 必須是函數
傳入 Vue 構造器的多數選項都能用在 Vue.extend() 中,但有兩個例外:data 與 el。如果直接把同一個物件當作 data 傳給 Vue.extend(),所有實例將共用同一份資料,造成狀態互相污染。正確做法是傳入一個函數,讓它每次回傳新物件:
var MyComponent = Vue.extend({
data: function () {
return { a: 1 }
}
})
模板解析的限制
Vue 的模板是 DOM 模板,使用瀏覽器原生的解析器,因此必須是有效的 HTML 片段。而 HTML 本身對某些元素的內容有硬性規定:
a 不能包含其他互動元素(如按鈕、連結)
ul 和 ol 只能直接包含 li
select 只能包含 option 和 optgroup
table 只能直接包含 thead、tbody、tfoot、tr、caption、col、colgroup
tr 只能直接包含 th 和 td
這些限制在實務中會造成意料之外的結果。例如 <my-select><option>...</option></my-select> 並不是有效的模板,即使 my-select 最終會展開成 <select>...</select>。也就是說,自定義標籤不能用在 ul、select、table 這類對內部元素有限制的標籤裡,否則會被瀏覽器「提到」外面,導致渲染不正確。
解法是使用 is 屬性:
<table> <tr is="my-component"></tr> </table> // <template> 不能用在 <table> 內,此時應改用 <tbody> // <table> 可以有多個 <tbody> <table> <tbody v-for="item in items"> <tr>Even row</tr> <tr>Odd row</tr> </tbody> </table>
用 props 傳遞資料
組件實例的作用域是孤立的,父子之間不會自動共享資料,必須透過 props 明確傳遞。子組件要先宣告它期待哪些 props:
Vue.component('child', {
// 宣告 props
props: ['msg'],
// prop 可以用在模板內,也可以用 this.msg 存取
template: '<span>{{ msg }}</span>'
})
靜態傳值:
<child msg="hello!"</child>
動態綁定,父組件資料變動時會同步傳給子組件:
<div> <input v-model="parentMsg"> <child v-bind:my-message="parentMsg"</child> <!-- 簡寫:<child :my-message="parentMsg"</child> --> </div>
綁定類型
prop 預設是單向綁定:父組件變化會傳給子組件,反之則不會。這樣設計是為了防止子組件誤改父組件狀態。若確實需要雙向或單次綁定,可用修飾符顯式宣告:
<!-- 預設單向綁定 --> <child :msg="parentMsg"</child> <!-- 雙向綁定 --> <child :msg.sync="parentMsg"</child> <!-- 單次綁定 --> <child :msg.once="parentMsg"</child>
要特別小心的是,如果 prop 是物件或陣列,它是以「參照」傳遞的。子組件內部對它的修改會直接影響父組件狀態,無論採用哪一種綁定方式。這是最常見的狀態污染來源之一。
父子組件通訊
父鏈
子組件可用 this.$parent 存取父組件,根實例的後代可用 this.$root 存取;父組件則有 this.$children 陣列,包含所有子元素。
自定義事件
每個 Vue 實例都是一個事件觸發器,這套事件系統獨立於原生 DOM 事件:
使用 $on() 監聽事件;
使用 $emit() 觸發事件;
使用 $dispatch() 派發事件,沿父鏈冒泡;
使用 $broadcast() 廣播事件,向下傳給所有後代。
與 DOM 事件不同,Vue 事件在冒泡過程中第一次觸發回調後會自動停止,除非回調明確回傳 true。
<!-- 子組件模板 -->
<template id="child-template">
<input v-model="msg">
<button v-on:click="notify">Dispatch Event</button>
</template>
<!-- 父組件模板 -->
<div id="events-example">
<p>Messages: {{ messages | json }}</p>
<child></child>
</div>
// 註冊子組件:把當前訊息派發出去
Vue.component('child', {
template: '#child-template',
data: function () {
return { msg: 'hello' }
},
methods: {
notify: function () {
if (this.msg.trim()) {
this.$dispatch('child-msg', this.msg)
this.msg = ''
}
}
}
})
// 初始化父組件:收到訊息時推入陣列
var parent = new Vue({
el: '#events-example',
data: { messages: [] },
// 建立實例時,events 選項等同於呼叫 $on
events: {
'child-msg': function (msg) {
// 回調內的 this 自動綁定到註冊它的實例
this.messages.push(msg)
}
}
})
用 v-on 綁定自定義事件
更推薦的寫法是在模板中直接宣告事件處理器:
<child v-on:child-msg="handleIt"</child>
當子組件觸發 child-msg 事件時,父組件的 handleIt 方法就會被呼叫。這個分工很值得記住:所有影響父組件狀態的程式碼都放在父組件的 handleIt 中,子組件只負責觸發事件。如此一來資料流向單純,組件的責任界線也清楚。
子組件索引
用 v-ref 為子組件指定索引 ID,就能直接存取該實例:
<div id="parent">
<user-profile v-ref:profile></user-profile>
</div>
var parent = new Vue({ el: '#parent' })
// 存取子組件
var child = parent.$refs.profile
Slot 內容分發
內容分發指的是「把父組件的內容混合進子組件自己的模板」,做法是使用特殊的 <slot> 元素作為插槽。
編譯作用域
這是一個容易搞錯的地方:父組件模板的內容在父組件作用域內編譯,子組件模板的內容則在子組件作用域內編譯。分發的內容也屬於父組件作用域。
Vue.component('child-component', {
// 有效,因為是在正確的作用域內
template: '<div v-show="someChildProperty">Child</div>',
data: function () {
return { someChildProperty: true }
}
})
單一 slot
若子組件模板沒有包含 <slot>,父組件傳入的內容會被丟棄。反之,如果子組件只有一個無屬性的 slot,父組件的整個內容會被插入到該位置並取代它。
<slot> 標籤內的內容視為「回退內容」,在子組件作用域內編譯;當宿主元素為空且沒有內容可插入時才顯示。
假設 my-component 的模板如下:
<div> <h1>This is my component!</h1> <slot> 如果沒有分發內容則顯示我。 </slot> </div>
父組件模板:
<my-component> <p>This is some original content</p> <p>This is some more original content</p> </my-component>
渲染結果:
<div> <h1>This is my component!</h1> <p>This is some original content</p> <p>This is some more original content</p> </div>
具名 slot
<slot> 可以用 name 屬性指定分發位置,多個 slot 可有不同名稱,並與內容片段中帶有對應 slot 屬性的元素相互匹配。同時仍可保留一個匿名 slot 作為預設插槽,用來承接找不到對應位置的內容;若沒有預設 slot,這些內容將被丟棄。
動態組件
多個組件可以共用同一個掛載點,並動態切換。做法是使用保留元素 <component>,把它的 is 屬性綁定到一個變數:
new Vue({
el: 'body',
data: { currentView: 'home' },
components: {
home: { /* ... */ },
posts: { /* ... */ },
archive: { /* ... */ }
}
})
<component :is="currentView"> <!-- 當 vm.currentView 改變時,組件隨之切換 --> </component>
keep-alive
加上 keep-alive 可以把切換出去的組件保留在記憶體中,避免重新渲染、保留其狀態:
<component :is="currentView" keep-alive>
<!-- 非作用中的組件將被快取 -->
</component>
activate 鉤子
用來控制組件切換時的等待行為。要注意它只作用於動態組件切換或靜態組件初始化渲染的過程,不作用於用實例方法手動插入的情況。
Vue.component('activate-example', {
activate: function (done) {
var self = this;
loadDataAsync(function (data) {
self.someData = data;
done();
});
}
})
transition-mode
用於指定兩個動態組件之間如何過渡。預設情況下進入與離開會同時平滑進行,而這個屬性提供了另外兩種模式:
in-out:新組件先過渡進入,等它完成後當前組件才過渡出去。
out-in:當前組件先過渡出去,等它完成後新組件才過渡進入。
<!-- 先淡出再淡入 -->
<component :is="view" transition="fade" transition-mode="out-in">
</component>
.fade-transition {
transition: opacity .3s ease;
}
.fade-enter, .fade-leave {
opacity: 0;
}
總結:組件 API 的三個面向
prop 允許外部環境傳遞資料給組件;
事件允許組件觸發外部環境的 action;
slot 允許外部環境插入內容到組件的視圖結構中。
把這三者記牢,再搭配前述的註冊方式與作用域規則,就足以應付絕大多數的組件設計需求。本文所述為 Vue.js 1.x 時代的寫法,若使用 Vue 2 以上的版本,部分語法(如 .sync 修飾符、$dispatch、v-ref)已有對應的現代寫法,建議對照官方文件確認。