iT邦幫忙

2018 iT 邦幫忙鐵人賽
DAY 14
1
Modern Web

用範例理解 Vue.js系列 第 14

用範例理解 Vue.js #14:Component 簡介

Imgur

Component 簡介

Day2:用七個官方範例初步認識 Vue.js已經有看過 Component 的範例。Component 在 Vue 中扮演很重要的腳色,使我們可封裝重用程式碼,且同時具有極高的彈性。

如何使用 Component(元件)?

在 Vue 中元件有兩種註冊方式,全域區域

全域元件

要註冊一個全域元件,可以透過 Vue 的 Global API 實現,格式為Vue.component('tagName', {options})

複習一下 Day2 的第七個範例:

<div id="app-7">
  <ol>
    <todo-item
      v-for="item in groceryList"
      v-bind:todo="item"
      v-bind:key="item.id">
    </todo-item>
  </ol>
</div>
Vue.component('todo-item', {
  props: ['todo'],
  template: '<li>{{ todo.text }}</li>'
})

var app7 = new Vue({
  el: '#app-7',
  data: {
    groceryList: [
      { id: 0, text: 'Vegetables' },
      { id: 1, text: 'Cheese' },
      { id: 2, text: 'Whatever else humans are supposed to eat' }
    ]
  }
})

附上 fiddle (https://jsfiddle.net/hunterliu/6bmrr9ar/1/)

區域元件

區域註冊的方式則是將 Vue Component 放在 Vue Instance 的選項物件屬性components中,簡單把全域註冊的元件改為區域註冊,範例如下:

var app7 = new Vue({
  el: '#app-7',
  data: {
    groceryList: [
      { id: 0, text: 'Vegetables' },
      { id: 1, text: 'Cheese' },
      { id: 2, text: 'Whatever else humans are supposed to eat' }
    ]
  },
  components: {
    'todo-item': {
       props: ['todo'],
       template: '<li>{{ todo.text }}</li>'
    }
  }
})

附上 fiddle (https://jsfiddle.net/hunterliu/6bmrr9ar/2/)

DOM 模版的解析 (DOM Template Parsing Caveats)

當定義 Component 的時候有些注意事項,例如在 , , , 這些元素裡包含的元素是有限制的,像是 , , 只能出現在特定元素內部。

解決辦法可以使用特殊的is特性,範例如下:

附上 fiddle (https://jsfiddle.net/hunterliu/yp1a42tx/1/)

data必須為函式

代補

參考資料


上一篇
用範例理解 Vue.js #13:v-model and data binding
下一篇
用範例理解 Vue.js #15:實例 Component Dropdown
系列文
用範例理解 Vue.js30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言