元件簡介
元件系統是 Vue.js 中一個重要的概念,它提供了一種抽象,讓我們能用獨立、可重複使用的小元件來建構大型應用。任何類型的介面都可以抽象成一棵元件樹:

那什麼是元件呢?元件可以擴充 HTML 元素、封裝可重用的 HTML 程式碼,我們可以把它看作自訂的 HTML 元素。由於篇幅較大,我會把元件入門拆成兩篇,方便大家消化。
元件的建立與註冊
Vue.js 元件的使用有三個步驟:建立元件建構器、註冊元件、使用元件。

<!DOCTYPE html> <html> <body> <div id="app"> <!-- 3. #app是Vue實例掛載的元素,應該在掛載元素范圍內使用組件--> <my-component></my-component> </div> </body> <script src="js/vue.js"></script> <script> // 1.創建一個組件構造器 var myComponent = Vue.extend({ template: '<div>This is my first component!</div>' }) // 2.注冊組件,並指定組件的標簽,組件的HTML標簽為<my-component> Vue.component('my-component', myComponent) new Vue({ el: '#app' }); </script> </html>
運行結果如下:

可見使用元件與使用普通 HTML 元素並無二致。
理解元件的建立與註冊
特別注意第五點。下面程式碼在三處用了 <my-component>,但只有 #app1 與 #app2 下的才會渲染:
<!DOCTYPE html> <html> <body> <div id="app1"> <my-component></my-component> </div> <div id="app2"> <my-component></my-component> </div> <!--該組件不會被渲染--> <my-component></my-component> </body> <script src="js/vue.js"></script> <script> var myComponent = Vue.extend({ template: '<div>This is a component!</div>' }) Vue.component('my-component', myComponent) var app1 = new Vue({ el: '#app1' }); var app2 = new Vue({ el: '#app2' }) </script> </html>

全域註冊與區域註冊
用 Vue.component() 註冊的元件是全域的,可在任意 Vue 實例下使用。若不想全域註冊,或想讓元件用於其他元件內,可用選項物件的 components 屬性做區域註冊:
<!DOCTYPE html> <html> <body> <div id="app"> <!-- 3. my-component只能在#app下使用--> <my-component></my-component> </div> </body> <script src="js/vue.js"></script> <script> // 1.創建一個組件構造器 var myComponent = Vue.extend({ template: '<div>This is my first component!</div>' }) new Vue({ el: '#app', components: { // 2. 將myComponent組件注冊到Vue實例下 'my-component' : myComponent } }); </script> </html>
由於該元件註冊在 #app 對應的實例下,因此不能在其他實例中使用,否則瀏覽器會報錯。
父元件與子元件
我們可以在元件中定義並使用其他元件,這就構成了父子關係:
<!DOCTYPE html> <html> <body> <div id="app"> <parent-component> </parent-component> </div> </body> <script src="js/vue.js"></script> <script> var Child = Vue.extend({ template: '<p>This is a child component!</p>' }) var Parent = Vue.extend({ // 在Parent組件內使用<child-component>標簽 template :'<p>This is a Parent component</p><child-component></child-component>', components: { // 局部注冊Child組件,該組件只能在Parent組件內使用 'child-component': Child } }) // 全局注冊Parent組件 Vue.component('parent-component', Parent) new Vue({ el: '#app' }) </script> </html>
執行結果如下:

這裡 Child 元件是在 Parent 元件中註冊的,因此只能在 Parent 的 template 中使用。以下兩種用法是錯誤的:
1. 以子標籤形式寫在父元件標籤內
<div id="app"> <parent-component> <child-component></child-component> </parent-component> </div>
因為子元件註冊進父元件時,Vue.js 已編譯好父元件模板,父元件要渲染的 HTML 已確定。<parent-component>…</parent-component> 之間的內容相當於執行期才出現,其中的子標籤只會被當作普通 HTML,而 <child-component> 並非標準標籤,會被瀏覽器忽略。
2. 在父元件標籤外使用子元件
<div id="app"> <parent-component> </parent-component> <child-component> </child-component> </div>
執行後瀏覽器會提示錯誤。

元件註冊語法糖
上述註冊方式略顯繁瑣,Vue.js 提供了語法糖簡化流程。用 Vue.component() 直接建立並註冊:
// 全局注冊,my-component1是標簽名稱 Vue.component('my-component1',{ template: '<div>This is the first component!</div>' }) var vm1 = new Vue({ el: '#app1' })
此時 Vue 會在背後自動呼叫 Vue.extend()。也可在 components 屬性中做區域註冊:
var vm2 = new Vue({ el: '#app2', components: { // 局部注冊,my-component2是標簽名稱 'my-component2': { template: '<div>This is the second component!</div>' }, // 局部注冊,my-component3是標簽名稱 'my-component3': { template: '<div>This is the third component!</div>' } } })
使用 script 或 template 標籤
語法糖雖簡化了註冊,但在 template 選項中拼接 HTML 仍不方便,也造成 HTML 與 JavaScript 高耦合。所幸 Vue.js 提供兩種方式把模板分離出來。
使用 <script> 標籤:
<!DOCTYPE html> <html> <body> <div id="app"> <my-component></my-component> </div> <script type="text/x-template" id="myComponent"> <div>This is a component!</div> </script> </body> <script src="js/vue.js"></script> <script> Vue.component('my-component',{ template: '#myComponent' }) new Vue({ el: '#app' }) </script> </html>
此時 template 選項不再是一段 HTML,而是一個 id,Vue.js 會依這個 id 找到對應元素,把其中的 HTML 作為模板編譯。

注意:type 設為 text/x-template 是為了告訴瀏覽器這不是一段 js,解析 HTML 時會忽略其中的內容。

使用 <template> 標籤則不需指定 type:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> </head> <body> <div id="app"> <my-component></my-component> </div> <template id="myComponent"> <div>This is a component!</div> </template> </body> <script src="js/vue.js"></script> <script> Vue.component('my-component',{ template: '#myComponent' }) new Vue({ el: '#app' }) </script> </html>
理解元件建立與註冊後,建議用 <script> 或 <template> 標籤定義模板,讓 HTML 與 JavaScript 分離,便於閱讀與維護。此外,Vue.js 也支援 .vue 檔,這部分留待後續文章介紹。
元件的 el 與 data 選項
傳入 Vue 建構器的多數選項也能用在 Vue.extend() 或 Vue.component() 中,但有兩個特例:data 和 el。Vue.js 規定:定義元件時,data 與 el 必須使用函式。以下程式執行時瀏覽器會報錯:
Vue.component('my-component', { data: { a: 1 } })

此外,若 data 指向某個物件,意味著所有元件實例共用同一份 data。應改用函式作為 data,讓它回傳一個新物件:
Vue.component('my-component', { data: function(){ return {a : 1} } })
使用 props
元件實例的作用域是獨立的,不能在子元件模板中直接引用父元件資料,此時可用 props 把資料傳給子元件。
props 基礎範例
var vm = new Vue({ el: '#app', data: { name: 'keepfool', age: 28 }, components: { 'my-component': { template: '#myComponent', props: ['myName', 'myAge'] } } })
可以把這個 Vue 實例看作 my-component 的父元件。若要在子元件中使用父元件資料,必須先在子元件宣告 props 屬性。
子元件的 HTML 模板:
<template id="myComponent"> <table> <tr> <th colspan="2"> 子組件數據 </th> </tr> <tr> <td>my name</td> <td>{{ myName }}</td> </tr> <tr> <td>my age</td> <td>{{ myAge }}</td> </tr> </table> </template>
透過已定義的 props 把父元件資料傳給子元件:
<div id="app"> <my-component v-bind:my-name="name" v-bind:my-age="age"></my-component> </div>
注意:在子元件中定義 prop 時使用了 camelCase 命名法,由於 HTML 特性不分大小寫,用作特性時需轉為 kebab-case(短橫線分隔),例如 myName 用作特性時要寫成 my-name。
執行結果如下:

父元件傳資料給子元件的語法為:
<child-component v-bind:子組件prop="父組件數據屬性"></child-component>
prop 的綁定類型
單向綁定:prop 預設是單向綁定,父元件屬性變化會傳給子元件,反之則不會,這是為了防止子元件無意間改動父元件狀態。因此修改子元件資料不影響父元件,而修改父元件資料會同步影響子元件。
雙向綁定:可用 .sync 顯式指定雙向綁定,讓子元件的改動回傳給父元件:
<my-component v-bind:my-name.sync="name" v-bind:my-age.sync="age"></my-component>

單次綁定:可用 .once 指定單次綁定,建立後不再同步後續變化:
<my-component v-bind:my-name.once="name" v-bind:my-age.once="age"></my-component>

範例
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> <link rel="stylesheet" href="styles/demo.css" /> </head> <body> <div id="app"> <div id="searchBar"> Search <input type="text" v-model="searchQuery" /> </div> <simple-grid :data="gridData" :columns="gridColumns" :filter-key="searchQuery"> </simple-grid> </div> <template id="grid-template"> <table> <thead> <tr> <th v-for="col in columns"> {{ col | capitalize}} </th> </tr> </thead> <tbody> <tr v-for="entry in data | filterBy filterKey"> <td v-for="col in columns"> {{entry[col]}} </td> </tr> </tbody> </table> </template> </body> <script src="js/vue.js"></script> <script> Vue.component('simple-grid', { template: '#grid-template', props: { data: Array, columns: Array, filterKey: String } }) var demo = new Vue({ el: '#app', data: { searchQuery: '', gridColumns: ['name', 'age', 'sex'], gridData: [{ name: 'Jack', age: 30, sex: 'Male' }, { name: 'Bill', age: 26, sex: 'Male' }, { name: 'Tracy', age: 22, sex: 'Female' }, { name: 'Chris', age: 36, sex: 'Male' }] } }) </script> </html>
這個範例還用到了兩個知識點:
props: { data: Array, columns: Array, filterKey: String } 表示父元件傳來的 data 與 columns 必須是陣列、filterKey 必須是字串。
總結
使用元件的前提是建立並註冊元件。本文詳細介紹了元件從建立到使用的步驟,幾種不同的註冊方式,以及用於父子傳值的 props 選項,最後以一個小範例演示了這些知識點。