組件系統是 Vue.js 另一個重要概念,因為它提供了一種抽象,讓我們可以用獨立可復用的小組件來構建大型應用。如果我們考慮到這點,幾乎任意類型的應用的界面都可以抽象為一個組件樹:
在 Vue 里,一個組件實質上是一個擁有預定義選項的一個 Vue 實例:
// Define a new component called todo-item Vue.component('todo-item', { template: '<li>This is a todo</li>' })
現在你可以在另一個組件模板中寫入它:
<ol> <!-- Create an instance of the todo-item component --> <todo-item></todo-item> </ol>
但是這樣會為每個 todo 渲染同樣的文本,這看起來並不是很酷。應該將數據從父作用域傳到子組件。來修改一下組件的定義,使得它能夠接受一個 prop
字段:
Vue.component('todo-item', { // The todo-item component now accepts a // "prop", which is like a custom attribute. // This prop is called todo. props: ['todo'], template: '<li>{{ todo.text }}</li>' })
現在,我們可以使用 v-bind
指令將 todo 傳到每一個重復的組件中:
<div id="app-7"> <ol> <!-- Now we provide each todo-item with the todo object --> <!-- it's representing, so that its content can be dynamic --> <todo-item v-for="item in groceryList" v-bind:todo="item"></todo-item> </ol> </div>
完整代碼如下:
Vue.component('todo-item', { props: ['todo'], template: '<li>{{ todo.text }}</li>' }) var app7 = new Vue({ el: '#app-7', data: { groceryList: [ { text: 'Vegetables' }, { text: 'Cheese' }, { text: 'Whatever else humans are supposed to eat' } ] } })

這只是一個假設的例子,但是我們已經將應用分割成了兩個更小的單元,子元素通過 props
接口實現了與父親元素很好的解耦。我們現在可以在不影響到父應用的基礎上,進一步為我們的 todo
組件改進更多復雜的模板和邏輯。
在一個大型應用中,為了使得開發過程可控,有必要將應用整體分割成一個個的組件。在后面的教程中我們將詳述組件,不過這里有一個(假想)的例子,看看使用了組件的應用模板是什么樣的:
<div id="app"> <app-nav></app-nav> <app-view> <app-sidebar></app-sidebar> <app-content></app-content> </app-view> </div>