元件簡介
元件系統是Vue.js其中一個重要的概念,它提供了一種抽象,讓我們可以使用獨立可複用的小元件來構建大型應用,任意型別的應用介面都可以抽象為一個元件樹:
那麼什麼是元件呢?
元件可以擴充套件HTML元素,封裝可重用的HTML程式碼,我們可以將元件看作自定義的HTML元素。
本文的Demo和原始碼已放到GitHub,如果您覺得本篇內容不錯,請點個贊,或在GitHub上加個星星!
(所有示例都放在GitHub Pages上了,請訪問https://github.com/keepfool/vue-tutorials檢視示例彙總)
由於元件的篇幅較大,我將會把元件的入門知識分為兩篇來講解,這樣也便於各位看官們快速消化。
元件的建立和註冊
基本步驟
Vue.js的元件的使用有3個步驟:建立元件構造器、註冊元件和使用元件。
下面的程式碼演示了這3個步驟:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
<!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元素沒什麼區別。
理解元件的建立和註冊
我們用以下幾個步驟來理解元件的建立和註冊:
Vue.extend()
是Vue構造器的擴充套件,呼叫Vue.extend()
建立的是一個元件構造器,而不是一個具體的元件例項。2.
Vue.extend()
構造器有一個選項物件,選項物件的template
屬性用於定義元件要渲染的HTML。3. 使用
Vue.component()
註冊元件時,需要提供2個引數,第1個引數時元件的標籤,第2個引數是元件構造器。4.
Vue.component()
方法內部會呼叫元件構造器,建立一個元件例項。5. 元件應該掛載到某個Vue例項下,否則它不會生效。
請注意第5點,以下程式碼在3個地方使用了<my-component>標籤,但只有#app1和#app2下的<my-component>標籤才起到作用。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
<!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屬性實現區域性註冊。
上面的示例可以改為區域性註冊的方式:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
<!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> |
由於my-component元件是註冊在#app元素對應的Vue例項下的,所以它不能在其它Vue例項下使用。
1 2 3 4 5 6 7 8 9 10 |
<div id="app2"> <!-- 不能使用my-component元件,因為my-component是一個區域性元件,它屬於#app--> <my-component></my-component> </div> <script> new Vue({ el: '#app2' }); </script> |
如果你這樣做了,瀏覽器會提示一個錯誤:
父元件和子元件
我們可以在元件中定義並使用其他元件,這就構成了父子元件的關係。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
<!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> |
這段程式碼的執行結果如下:
我們分幾個步驟來理解這段程式碼:
var Child = Vue.extend(...)
定義一了個Child元件構造器var Parent = Vue.extend(...)
定義一個Parent元件構造器components: { 'child-component': Child }
,將Child元件註冊到Parent元件,並將Child元件的標籤設定為child-component
。template :'<p>This is a Parent component</p><child-component></child-component>'
,在Parent元件內以標籤的形式使用Child元件。Vue.component('parent-component', Parent)
全域性註冊Parent元件- 在頁面中使用<parent-component>標籤渲染Parent元件的內容,同時Child元件的內容也被渲染出來
Child元件是在Parent元件中註冊的,它只能在Parent元件中使用,確切地說:子元件只能在父元件的template中使用。
請注意下面兩種子元件的使用方式是錯誤的:
1. 以子標籤的形式在父元件中使用
1 2 3 4 5 |
<div id="app"> <parent-component> <child-component></child-component> </parent-component> </div> |
為什麼這種方式無效呢?因為當子元件註冊到父元件時,Vue.js會編譯好父元件的模板,模板的內容已經決定了父元件將要渲染的HTML。
<parent-component>…</parent-component>
相當於執行時,它的一些子標籤只會被當作普通的HTML來執行,<child-component></child-component>不是標準的HTML標籤,會被瀏覽器直接忽視掉。
2. 在父元件標籤外使用子元件
1 2 3 4 5 6 |
<div id="app"> <parent-component> </parent-component> <child-component> </child-component> </div> |
執行這段程式碼,瀏覽器會提示以下錯誤
元件註冊語法糖
以上元件註冊的方式有些繁瑣,Vue.js為了簡化這個過程,提供了註冊語法糖。
使用Vue.component()直接建立和註冊元件:
1 2 3 4 5 6 7 8 |
// 全域性註冊,my-component1是標籤名稱 Vue.component('my-component1',{ template: '<div>This is the first component!</div>' }) var vm1 = new Vue({ el: '#app1' }) |
Vue.component()
的第1個引數是標籤名稱,第2個引數是一個選項物件,使用選項物件的template屬性定義元件模板。
使用這種方式,Vue在背後會自動地呼叫Vue.extend()
。
在選項物件的components屬性中實現區域性註冊:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
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提供了兩種方式將定義在JavaScript中的HTML模板分離出來。
使用<script>標籤
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
<!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作為模板進行編譯。
注意:使用<script>標籤時,type指定為text/x-template,意在告訴瀏覽器這不是一段js指令碼,瀏覽器在解析HTML文件時會忽略<script>標籤內定義的內容。
使用<template>標籤
如果使用<template>
標籤,則不需要指定type屬性。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
<!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模板。
這使得HTML程式碼和JavaScript程式碼是分離的,便於閱讀和維護。
另外,在Vue.js中,可建立.vue字尾的檔案,在.vue檔案中定義元件,這個內容我會在後面的文章介紹。
元件的el和data選項
傳入Vue構造器的多數選項也可以用在 Vue.extend()
或Vue.component()
中,不過有兩個特例: data
和el
。
Vue.js規定:在定義元件的選項時,data和el選項必須使用函式。
下面的程式碼在執行時,瀏覽器會提出一個錯誤
1 2 3 4 5 |
Vue.component('my-component', { data: { a: 1 } }) |
另外,如果data選項指向某個物件,這意味著所有的元件例項共用一個data。
我們應當使用一個函式作為 data 選項,讓這個函式返回一個新物件:
1 2 3 4 5 |
Vue.component('my-component', { data: function(){ return {a : 1} } }) |
使用props
元件例項的作用域是孤立的。這意味著不能並且不應該在子元件的模板內直接引用父元件的資料。可以使用 props 把資料傳給子元件。
props基礎示例
下面的程式碼定義了一個子元件my-component,在Vue例項中定義了data選項。
1 2 3 4 5 6 7 8 9 10 11 12 13 |
var vm = new Vue({ el: '#app', data: { name: 'keepfool', age: 28 }, components: { 'my-component': { template: '#myComponent', props: ['myName', 'myAge'] } } }) |
為了便於理解,你可以將這個Vue例項看作my-component的父元件。
如果我們想使父元件的資料,則必須先在子元件中定義props屬性,也就是props: ['myName', 'myAge']
這行程式碼。
定義子元件的HTML模板:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
<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屬性傳遞給子元件:
1 2 3 |
<div id="app"> <my-component v-bind:my-name="name" v-bind:my-age="age"></my-component> </div> |
注意:在子元件中定義prop時,使用了camelCase命名法。由於HTML特性不區分大小寫,camelCase的prop用於特性時,需要轉為 kebab-case(短橫線隔開)。例如,在prop中定義的myName,在用作特性時需要轉換為my-name。
這段程式的執行結果如下:
父元件是如何將資料傳給子元件的呢?相信看了下面這圖,也許你就能很好地理解了。
在父元件中使用子元件時,通過以下語法將資料傳遞給子元件:
1 |
<child-component v-bind:子元件prop="父元件資料屬性"></child-component> |
prop的繫結型別
單向繫結
既然父元件將資料傳遞給了子元件,那麼如果子元件修改了資料,對父元件是否會有所影響呢?
我們將子元件模板和頁面HTML稍作更改:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
<div id="app"> <table> <tr> <th colspan="3">父元件資料</td> </tr> <tr> <td>name</td> <td>{{ name }}</td> <td><input type="text" v-model="name" /></td> </tr> <tr> <td>age</td> <td>{{ age }}</td> <td><input type="text" v-model="age" /></td> </tr> </table> <my-component v-bind:my-name="name" v-bind:my-age="age"></my-component> </div> <template id="myComponent"> <table> <tr> <th colspan="3">子元件資料</td> </tr> <tr> <td>my name</td> <td>{{ myName }}</td> <td><input type="text" v-model="myName" /></td> </tr> <tr> <td>my age</td> <td>{{ myAge }}</td> <td><input type="text" v-model="myAge" /></td> </tr> </table> </template> |
執行這個頁面,我們做兩個小試驗:
1. 在頁面上修改子元件的資料
修改了子元件的資料,沒有影響父元件的資料。
2. 在頁面上修改父元件的資料
修改了父元件的資料,同時影響了子元件。
雙向繫結
可以使用.sync
顯式地指定雙向繫結,這使得子元件的資料修改會回傳給父元件。
1 |
<my-component v-bind:my-name.sync="name" v-bind:my-age.sync="age"></my-component> |
單次繫結
可以使用.once
顯式地指定單次繫結,單次繫結在建立之後不會同步之後的變化,這意味著即使父元件修改了資料,也不會傳導給子元件。
1 |
<span class="hljs-tag"><<span class="hljs-title">my-component</span> <span class="hljs-attribute">v-bind:my-name.once</span>=<span class="hljs-value">"name"</span> <span class="hljs-attribute">v-bind:my-age.once</span>=<span class="hljs-value">"age"</span>></span><span class="hljs-tag"></<span class="hljs-title">my-component</span>></span> |
示例
為了儘快消化這些知識,我們來做一個小示例吧。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 |
<!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> |
除了以上介紹的知識點,這個示例還用到了兩個知識點:
1. prop驗證
1 2 3 4 5 |
props: { data: Array, columns: Array, filterKey: String } |
這段程式碼表示:父元件傳遞過來的data和columns必須是Array型別,filterKey必須是字串型別。
更多prop驗證的介紹,請參考:官方文件prop驗證
2. filterBy過濾器
可以根據指定的字串過濾資料。
總結
使用元件的前提是建立並註冊元件,本篇文章詳細介紹了元件從建立到使用的步驟,並介紹了幾種不同的方式去建立和註冊元件;然後介紹了元件的props選項,它用於將父元件的資料傳遞給子元件,最後我們用一個小的示例演示了這些知識點。