DIV CSS 佈局教程網

深入解析 Vue.js 組件的核心概念與實作
編輯:關於JavaScript     

組件是什麼:組件堪稱 Vue.js 最具威力的特性之一。它能夠擴充既有的 HTML 元素,把可重複使用的程式邏輯打包在一起。從宏觀角度來看,組件其實就是自訂的 DOM 元素,Vue.js 的編譯器會為它們注入專屬的功能;在某些情境下,組件也能以原生 HTML 元素的形態出現,透過 is 屬性來完成擴充。

如何註冊組件?

通常的做法是先以 Vue.extend 建立一個組件,再利用 Vue.component 完成註冊。Vue.extend 的基本寫法如下:

 var MyComponent = Vue.extend({ // 這裡可以放入各種選項 }) 

如果希望在其他地方也能使用這個組件,就得先幫它取個名字:

Vue.component('my-component', MyComponent)

命名完成後,就能像操作一般 DOM 元素那樣,在 HTML 標籤裡直接使用這個組件名稱。下面是一個完整的註冊與使用範例。

HTML 部分:

 <div id="example"> <my-component></my-component> </div> 

JS 部分:

 // 定義 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 

巢狀組件
組件本身也能內含其他組件。以下範例中,parent 組件裡就包了一個名為 child-component 的子組件,不過這個子組件僅能被 parent 組件使用:

 var child = Vue.extend({ template: '<div>A custom component!</div>' }); var parent = Vue.extend({ template: '<div>Parent Component: <child-component></child-component></div>', components: { 'child-component': child } }); Vue.component("parent-component", parent); 

上面這種定義方式顯得有些繁瑣,其實我們也可以省略 Vue.component 與 Vue.extend 的層層呼叫:

 // 在一個步驟中完成擴展與註冊 Vue.component('my-component', { template: '<div>A custom component!</div>' }) // 局部註冊也能這樣寫 var Parent = Vue.extend({ components: { 'my-component': { template: '<div>A custom component!</div>' } } }) 

動態組件

多個組件可以共用同一個掛載點,並在它們之間動態切換。做法是使用保留的 <component> 元素,將它動態綁定到 is 屬性上。下面的範例在同一個 Vue 實例中掛載了 home、posts、archive 三個組件,透過 currentView 屬性來切換顯示的內容。

HTML 部分:

 <div id="dynamic"> <button id="home">Home</button> <button id="posts">Posts</button> <button id="archive">Archive</button> <br> <component :is="currentView"></component> </div> 

JS 部分:

 var vue = new Vue({ el:"#dynamic", data: { currentView: "home" }, components: { home:{ template: "Home" }, posts: { template: "Posts" }, archive: { template: "Archive" } } }); document.getElementById("home").onclick = function(){ vue.currentView = "home"; }; document.getElementById("posts").onclick = function(){ vue.currentView = "posts"; }; document.getElementById("archive").onclick = function(){ vue.currentView = "archive"; }; 

組件與 v-for 的搭配
<my-component v-for="item in items"></my-component>

由於組件的作用域是彼此獨立的,因此無法直接把資料傳給組件。要達到傳遞的目的,就必須借助 props:

<my-component
v-for="item in items"
:item="item"
:index="$index">
</my-component>

之所以不自動把 item 注入組件,是因為這樣會讓組件和當前的 v-for 過度綁死。明確宣告資料的來源,反而能讓組件在其他場景中輕鬆複用。

深入響應式原理

在組件中綁定資料時,怎樣才能綁得既有效率,又能支援動態修改與新增屬性?我們來看看背後的原理。

如何追蹤變化:當你把一個不同的物件當作 data 傳給 Vue 實例時,Vue.js 會逐一走訪它的屬性,並用 Object.defineProperty 把它們轉換成 getter/setter。這是 ES5 的特性,也因此 Vue.js 不支援 IE8 及更低版本的瀏覽器。

模板裡的每一個指令與資料綁定,都對應著一個 watcher 物件;在計算的過程中,watcher 會把用到的屬性記錄為依賴。等到日後這些依賴的 setter 被呼叫時,就會觸發 watcher 重新計算。流程如下圖所示:


變化檢測的難題:Vue.js 無法偵測物件屬性的新增或刪除,屬性必須事先存在於 data 上,Vue.js 才能把它轉換成 getter/setter 模式,進而具備響應能力。舉例來說:

 var data = { a: 1 }; var vm = new Vue({ data: data }); // `vm.a` 和 `data.a` 現在是響應的 vm.b = 2 // `vm.b` 不是響應的 data.b = 2 // `data.b` 不是響應的 

不過,還是有辦法在實例建立之後新增屬性,並讓它具備響應能力,那就是使用 set(key, value) 實例方法:

vm.$set('b', 2)
// `vm.b` 和 `data.b` 現在是響應的

對於一般物件,則可以使用全域方法 Vue.set(object, key, value):
Vue.set(data, 'c', 3)
// `vm.c` 和 `data.c` 現在是響應的

初始化資料:儘管 Vue.js 提供了動態新增響應屬性的能力,官方仍建議在 data 物件上把所有響應屬性一次宣告清楚。

不建議這樣寫:

 var vm = new Vue({ template: '<div>{{msg}}</div>' }) // 然後才補上 `msg` vm.$set('msg', 'Hello!') 

應該這樣寫:

 var vm = new Vue({ data: { // 先用空值把 `msg` 宣告出來 msg: '' }, template: '<div>{{msg}}</div>' }) // 之後再賦值 vm.msg = 'Hello!' 

組件完整案例
接著介紹一個實作模態視窗的完整範例,程式碼並不複雜。

HTML 部分:

 <!-- 用 script 定義一個模板 --> <script type="x/template" id="modal-template"> <!--模板是否顯示透過 v-show="show" 控制,transition 負責動畫效果--> <div class="modal-mask" v-show="show" transition="modal"> <div class="modal-wrapper"> <div class="modal-container"> <div class="modal-header"> <!--slot 相當於 header 的佔位符--> <slot name="header"> default header </slot> </div> <div class="modal-body"> <!--slot 相當於 body 的佔位符--> <slot name="body"> default body </slot> </div> <div class="modal-footer"> <!--slot 相當於 footer 的佔位符--> <slot name="footer"> default footer </slot> <button class="modal-default-button" @click="show = false">OK</button> </div> </div> </div> </div> </script> <div id="app"> <!--點擊按鈕時把 vue 實例的 showModal 特性設為 true--> <button id="show-modal" @click="showModal = true">show modal</button> <!--modal 是自訂的組件,它的 show 特性綁定到 vue 實例的 showModal--> <modal :show.sync="showModal"> <!--替換 modal 中 slot 為 header 的內容--> <h3 slot="header">Custom Header</h3> </modal> </div> 

JS 部分:

 //定義一個組件,名稱為 modal Vue.component("modal", { //模板綁定 id 為 modal-template 的 DOM 元素內容 template: "#modal-template", props: { //特性,型別為布林 show:{ type: Boolean, required: true, twoWay: true } } }); //實例化 vue,作用域在 id 為 app 的元素下 new Vue({ el: "#app", data: { //特性,預設值為 false showModal: false } }); 

CSS 部分:

 .modal-mask { position: fixed; z-index: 9998; top: 0; left: 0; width: 100%; height: 100%; background-color: rgba(0, 0, 0, .5); display: table; transition: opacity .3s ease; } .modal-wrapper { display: table-cell; vertical-align: middle; } .modal-container { width: 300px; margin: 0px auto; padding: 20px 30px; background-color: #fff; border-radius: 2px; box-shadow: 0 2px 8px rgba(0, 0, 0, .33); transition: all .3s ease; font-family: Helvetica, Arial, sans-serif; } .modal-header h3 { margin-top: 0; color: #42b983; } .modal-body { margin: 20px 0; } .modal-default-button { float: right; } /* * 以下樣式會在 v-transition="modal" 的元素可見性切換時 * 由 Vue.js 自動套用。 * * 你可以透過編輯這些樣式來調整模態視窗的過場動畫。 */ .modal-enter, .modal-leave { opacity: 0; } .modal-enter .modal-container, .modal-leave .modal-container { -webkit-transform: scale(1.1); transform: scale(1.1); } 

由於筆者在實際專案裡對組件的運用還不算深入,因此這篇整理偏向基礎介紹,若有理解不精之處,還請各位多多包涵,也感謝大家的閱讀。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved