DIV CSS 佈局教程網

Vue.js 入門教程(下):組件與 Props 數據傳遞
編輯:關於JavaScript     

接上一篇的進度,這次把組件系統和組件間通信講清楚。

4. 組件使用基礎

組件可以理解為可重用的自定義 HTML。用一批組件就能搭出大型應用,任意類型的界面都可以抽象成一個組件樹:

組件代碼可以按 template、style、script 拆分,放到對應的 .vue 文件裡。預定義選項中最核心的幾個:模板(template)、初始數據(data)、接受的外部參數(props)、方法(methods)、生命週期鉤子(lifecycle hooks)。

4.1 基本步驟

先創建構造器:

var MyComponent = Vue.extend({
  // 選項...
})

再用 Vue.component(tag, constructor) 全局註冊:

//全局注冊組件,tag 為 my-component
Vue.component('my-component', MyComponent)

然後在模板裡使用:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<div id="xxx">
  <my-component></my-component>
</div>
<script src="js/vue.js"></script>
<script>
var myComponent = Vue.extend({
  template: '<p>9898不得了!</p>'
});
Vue.component('my-component', myComponent);
new Vue({ el: '#xxx' });
</script>
</body>
</html>

幾點說明:全局註冊的第一個參數是組件名,第二個是構造函數;template 定義組件要渲染的 HTML;組件模板會替換掉自定義元素本身,自定義元素只是充當掛載點,組件必須掛在 Vue 實例上才會生效。

自定義標籤名 Vue.js 並不強制遵循 W3C 規則(小寫且含一個短橫線),但為了避免麻煩,建議還是遵守。

4.2 局部註冊

用實例的 components 選項註冊:

<div id="xxx">
  <my-component></my-component>
</div>
<script src="js/vue.js"></script>
<script>
var myComponent = Vue.extend({
  template: '<p>9898不得了!</p>'
});
new Vue({
  el: '#xxx',
  components: { 'my-component': myComponent }
});
</script>

也可以在組件裡定義並使用其他組件:

<div id="example">
  <xx-component></xx-component>
</div>
<script src="js/vue.js"></script>
<script>
var Child = Vue.extend({
  template: '<div>i am zai</div>',
  replace: true
});

var Parent = Vue.extend({
  template: '<p>i am baba</p><br/><wa></wa>',
  components {
    // <xx-component> 只能用在父組件模板內
    'wa': Child
  }
});

new Vue({
  el: '#example',
  components: { 'xx-component': Parent }
});
</script>

重點:子組件只能在父組件的 template 中使用。

還有簡化寫法,Vue 會在背後自動調用 Vue.extend():

<div id="xxx">
  <my-component-continue></my-component-continue>
</div>
<script src="js/vue.js"></script>
<script>
var vm2 = new Vue({
  el: '#xxx',
  components: {
    'my-component': { template: '<div>9898不得了!</div>' },
    'my-component-continue': { template: '<div>糧食大豐收!</div>' }
  }
});
</script>

4.3 組件選項的坑

定義組件選項時,data 必須使用函數。如果 data 指向某個對象,所有組件實例會共用同一份數據,這顯然不是想要的:

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

同理,el 選項寫在 Vue.extend() 裡時也必須是函數。

5. 數據傳遞

Vue.js 組件之間有三種數據傳遞方式:props、組件通信、slot。

5.1 props

props 是組件數據的一個字段,期望從父組件傳下來。因為組件實例的作用域是孤立的,子組件必須顯式用 props 選項才能拿到父組件的數據。

(1)字面量

<child msg="hello!"></child>
<script src="js/vue.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript">
Vue.component('child', {
  props: ['msg'],                     //聲明 props
  template: '<span>{{ msg }}你困嗎</span>'   //prop 可用於模板,也可用 this.msg 設置
});
new Vue({ el: 'body' });
</script>

注意 HTML 特性不區分大小寫,camelCase 形式的 prop 寫到標籤上時要轉成 kebab-case:

Vue.component('child', {
  props: ['myMessage'],               //camelCase in JavaScript
  template: '<span>{{ myMessage }}</span>'
});

<!-- kebab-case in HTML -->
<child my-message="hello!"></child>

(2)動態綁定

類似用 v-bind 綁定 HTML 特性到表達式,也可以用 v-bind 綁定動態 props 到父組件的數據,父組件變化時會傳導給子組件:

<div>
  <input v-model="parentMsg">
  <br>
  <child :my-message="parentMsg"></child>
</div>
<script src="js/vue.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript">
Vue.component('child', {
  props: ['myMessage'],
  template: '<span>{{ myMessage }}你困嗎</span>'
});
new Vue({
  el: 'body',
  data: { parentMsg: '' }
});
</script>

在輸入框裡敲字的時候,子組件的內容會同步變化:

(3)綁定類型

可以用綁定修飾符:

<!-- 默認為單向綁定 -->
<child :msg="parentMsg"></child>

<!-- 雙向綁定 -->
<child :msg.sync="parentMsg"></child>

<!-- 單次綁定 -->
<child :msg.once="parentMsg"></child>

prop 默認單向:父組件屬性變化會傳給子組件,反過來不行。

但要注意:如果 prop 是對象或數組,是按引用傳遞。子組件內部修改它會影響父組件的狀態,這跟用哪種綁定類型無關。

綜合示例:

<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.sync="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>

<script src="js/vue.js"></script>
<script>
var vm = new Vue({
  el: '#app',
  data: { name: 'k', age: 24 },
  components: {
    'my-component': {
      template: '#myComponent',
      props: ['myName', 'myAge']
    }
  }
});
</script>

上面這段裡,name 是雙向綁定,age 是單向綁定:

5.2 過濾器與循環渲染

下面是一個稍複雜的例子,用雙重 v-for 渲染表格:

<tr v-for="entry in data | filterBy filterKey">
  <td v-for="col in columns"> {{ entry[col] }} </td>
</tr>

外層 tr 遍歷 data 的條數(entry 代表每一行),內層 td 遍歷 columns 的數量(col 代表每一列),entry[col] 取出具體數據。| filterBy filterKey 過濾搜索關鍵詞,| capitalize 則能把首字母轉大寫。

props 也可以做類型校驗:

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

意思是父組件傳過來的 data 和 columns 必須是數組,filterKey 必須是字符串。

更完整的校驗寫法:

Vue.component('example', {
  props: {
    // 基礎類型檢測(null 意味著任何類型都可以)
    propA: Number,

    // 多種類型(1.0.21+)
    propM: [String, Number],

    // 必需且是字符串
    propB: { type: String, required: true },

    // 數字,有默認值
    propC: { type: Number, default: 100 },

    // 對象/數組的默認值應當由一個函數返回
    propD: {
      type: Object,
      default: function () { return { msg: 'hello' } }
    },

    // 指定這個 prop 為雙向綁定
    // 如果綁定類型不對將拋出一條警告
    propE: { twoWay: true },

    // 自定義驗證函數
    propF: {
      validator: function (value) { return value > 10 }
    },

    // 轉換函數(1.0.12 新增),在設置值之前轉換值
    propG: {
      coerce: function (val) { return val + '' }        //轉為字符串
    },
    propH: {
      coerce: function (val) { return JSON.parse(val) } //JSON 字符串轉對象
    }
  }
})

type 可以是 String、Number、Boolean、Function、Object、Array 這些原生構造器,也可以是自定義構造器(用 instanceof 檢測)。

當 prop 校驗失敗時,Vue 會拒絕在子組件上設置此值,開發版本下還會拋出一條警告——這在排查「數據傳不進來」的問題時特別有用。

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