DIV CSS 佈局教程網

Vue.js 組件完整入門:從建立、註冊到 props 傳值
編輯:關於JavaScript     

一、為什麼需要組件

組件系統是 Vue.js 最重要的概念之一。它提供了一種抽象,讓我們能用獨立、可重複使用的小組件來拼出大型應用 —— 幾乎任何型別的介面都可以被抽象成一棵組件樹:

簡單說:組件可以擴充 HTML 元素,把可重複使用的 HTML 程式碼封裝起來,我們可以把它看作自訂的 HTML 標籤。

二、建立與註冊的三個步驟

建立組件構造器 → 註冊組件 → 使用組件。

<!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. 註冊組件,並指定標籤名稱
Vue.component('my-component', myComponent);

new Vue({ el: '#app' });
</script>
</html>

執行結果:

可以看到,使用組件和使用普通 HTML 元素沒有任何差別。

逐點拆解

1. Vue.extend() 是 Vue 構造器的擴充,呼叫它得到的是一個組件構造器,不是具體的組件實例。
2. 傳入的選項物件中,template 屬性定義了組件要渲染的 HTML。
3. Vue.component() 需要兩個參數:第一個是標籤名稱,第二個是組件構造器。
4. Vue.component() 內部會呼叫構造器,建立組件實例。
5. 組件必須掛載在某個 Vue 實例之下才會生效。

第 5 點特別重要。下面的程式碼在三個地方用了 my-component,但只有 #app1 與 #app2 裡的會被渲染:

<div id="app1"><my-component></my-component></div>
<div id="app2"><my-component></my-component></div>
<!-- 這一個不會被渲染 -->
<my-component></my-component>

<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>

三、全域註冊與區域註冊

用 Vue.component() 註冊是全域的,任何 Vue 實例都能用。若不想全域註冊,或希望組件只在其他組件內使用,可以用選項物件的 components 屬性做區域註冊:

<div id="app">
  <!-- 3. my-component 只能在 #app 下使用 -->
  <my-component></my-component>
</div>
<script>
var myComponent = Vue.extend({ template: '<div>This is my first component!</div>' });

new Vue({
    el: '#app',
    components: {
        // 2. 區域註冊
        'my-component': myComponent
    }
});
</script>

此時若在別的實例裡使用它:

<div id="app2">
  <!-- 無法使用,my-component 屬於 #app -->
  <my-component></my-component>
</div>
<script>new Vue({ el: '#app2' });</script>

瀏覽器就會直接報錯:

四、父組件與子組件

在組件中定義並使用其他組件,就形成了父子關係:

<div id="app">
  <parent-component></parent-component>
</div>
<script>
var Child = Vue.extend({
    template: '<p>This is a child component!</p>'
});
var Parent = Vue.extend({
    // 在 Parent 的 template 內使用 child-component
    template: '<p>This is a Parent component</p><child-component></child-component>',
    components: {
        'child-component': Child     //區域註冊
    }
});
Vue.component('parent-component', Parent);   //全域註冊 Parent
new Vue({ el: '#app' });
</script>

執行結果:

看不懂的話,可以照這幾行對照:

1. var Child = Vue.extend(…) 定義 Child 構造器。
2. var Parent = Vue.extend(…) 定義 Parent 構造器。
3. components: { 'child-component': Child } 把 Child 註冊進 Parent,標籤名為 child-component。
4. Parent 的 template 中以標籤形式使用 Child。
5. Vue.component('parent-component', Parent) 全域註冊 Parent。
6. 頁面中使用 parent-component,Parent 與 Child 的內容都會被渲染。

結論:Child 是在 Parent 中註冊的,子組件只能在父組件的 template 裡使用。

兩種常見的錯誤寫法

1. 以子標籤形式寫在父組件標籤內

<div id="app">
  <parent-component>
    <child-component></child-component>
  </parent-component>
</div>

無效的原因是:組件註冊時 Vue 已經編譯好父組件的模板,父組件要渲染什麼 HTML 早就定了。parent-component 是「執行期」才展開的,它裡面的子標籤只會被當成普通 HTML 處理,而 child-component 不是標準標籤,會被瀏覽器直接忽略。

2. 在父組件標籤外使用子組件

<div id="app">
  <parent-component></parent-component>
  <child-component></child-component>
</div>

一樣會報錯:

五、註冊的語法糖

每次都先 extend 再 component 有點繁瑣,Vue 提供了簡化寫法。

用 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': { template: '<div>This is the second component!</div>' },
        'my-component3': { template: '<div>This is the third component!</div>' }
    }
});

用 script 或 template 標籤分離模板

語法糖雖然省事,但把 HTML 字串拼在 template 裡很難讀,也造成 HTML 與 JavaScript 的高耦合。Vue 提供了兩種把模板抽出來的方式。

使用 script 標籤:

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

<script type="text/x-template" id="myComponent">
  <div>This is a component!</div>
</script>

<script src="js/vue.js"></script>
<script>
Vue.component('my-component', { template: '#myComponent' });
new Vue({ el: '#app' });
</script>

此時 template 不再是 HTML 字串,而是一個 id,Vue 會依此找到對應元素,把裡面的 HTML 當模板編譯。

注意 type="text/x-template" 是為了告訴瀏覽器「這不是 JavaScript」,解析 HTML 時會跳過裡面的內容。

使用 template 標籤:不需要指定 type。

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

<template id="myComponent">
  <div>This is a component!</div>
</template>

<script src="js/vue.js"></script>
<script>
Vue.component('my-component', { template: '#myComponent' });
new Vue({ el: '#app' });
</script>

我的建議是養成用 script 或 template 標籤定義模板的習慣,讓 HTML 與 JavaScript 保持分離,可讀性與維護性都好得多。(另外 Vue 也支援 .vue 單檔組件,這個留待後續文章介紹。)

六、組件的 el 與 data 選項

傳入 Vue 構造器的大部分選項都能用在 Vue.extend() 或 Vue.component() 裡,但有兩個例外:data 與 el。在定義組件時,這兩個選項必須使用函式。

Vue.component('my-component', {
    data: { a: 1 }        //錯誤寫法
});

另外,如果 data 指向某個物件,所有組件實例會共用同一份資料。正確做法是讓函式回傳一個新物件:

Vue.component('my-component', {
    data: function () {
        return { a: 1 };
    }
});

七、用 props 傳值給子組件

組件實例的作用域是獨立的,因此不能、也不應該在子組件模板裡直接引用父組件的資料,必須透過 props 傳遞。

先建立一個 Vue 實例,可以把它當成 my-component 的父組件:

var vm = new Vue({
    el: '#app',
    data: { name: 'keepfool', age: 28 },
    components: {
        'my-component': {
            template: '#myComponent',
            props: ['myName', 'myAge']      //先宣告要接收的 props
        }
    }
});

子組件模板:

<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>

在父組件中把資料傳進去:

<div id="app">
  <my-component v-bind:my-name="name" v-bind:my-age="age"></my-component>
</div>

命名要注意:prop 宣告時用 camelCase(myName),但 HTML 標籤屬性不分大小寫,所以用作屬性時要轉成 kebab-case(my-name)。

執行結果:

傳值的流向大致如下圖:

語法可以記成:

<child-component v-bind:子組件prop="父組件數據屬性"></child-component>

prop 的三種綁定型別

單向綁定(預設)

把父子兩邊都加上 input 來測試:

<div id="app">
  <table>
    <tr><th colspan="3">父組件數據</th></tr>
    <tr><td>name</td><td>{{ name }}</td><td><input v-model="name" /></td></tr>
    <tr><td>age</td><td>{{ age }}</td><td><input 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">子組件數據</th></tr>
    <tr><td>my name</td><td>{{ myName }}</td><td><input v-model="myName" /></td></tr>
    <tr><td>my age</td><td>{{ myAge }}</td><td><input v-model="myAge" /></td></tr>
  </table>
</template>

在頁面上修改子組件的資料:

改了子組件,父組件不受影響。

反過來修改父組件的資料:

改了父組件,子組件同步變化。

這就是單向資料流:父 → 子會傳導,子 → 父不會。這樣設計是為了避免子組件在無意間改動父組件的狀態。

雙向綁定

加上 .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>
  <!-- 用 props 把資料、欄位與搜尋字串傳進子組件 -->
  <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>

<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>
</body>
</html>

這個範例另外用到兩個知識點:

1. prop 驗證

props: {
    data: Array,
    columns: Array,
    filterKey: String
}

代表父組件傳來的 data 與 columns 必須是陣列,filterKey 必須是字串。型別不符時 Vue 會在 console 發出警告。

2. filterBy 過濾器

可依指定字串過濾陣列資料,這裡讓搜尋框的內容直接驅動表格過濾。

總結

使用組件的前提是建立並註冊組件。本文從三個基本步驟出發,介紹了全域與區域註冊、父子組件的正確使用方式、語法糖與模板分離,接著說明 el/data 必須用函式的限制,最後透過 props 完成父子通訊與三種綁定型別,並用一個搜尋表格的範例收尾。

本文已整理進《Vue.js 前端組件學習教程》,歡迎延伸閱讀。以上就是全部內容,希望對你的學習有幫助。

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