iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 11
1
Modern Web

初探Vue.js 30天系列 第 11

[Day 11] Component 認識元件

Component介紹

元件(Component)是可複用的Vue Instance,並可以定義其名稱。/images/emoticon/emoticon07.gif
Vue.js應用程式都是以Instance為主,在加上許多元件組成的。

用蓋房子來比喻,Vue Instance就像地基,而磚塊、瓦片都是元件,最終會組成一間房屋。
每個元件都是各自獨立的Instance,裡面的data不會互相干擾,除了主動做元間的資料傳遞[Props, Emit]後面會提到。

https://ithelp.ithome.com.tw/upload/images/20200925/20108252sFdxj07qU6.jpg

註冊元件

當做出一個元件後,要拿來之前,必須在Vue Instance後註冊才能使用。
註冊又分為 全域註冊局部註冊

全域註冊(Global Registration)

Component的全域註冊,可以直接在頁面上呼叫Component。
使用Vue.component來註冊一個元件,在註冊全域元件時要給予兩個參數,分別為「元件名稱」及「元件物件」

<div id="app">
	<global-component></global-component>
</div>
Vue.component('global-component', {
  template:`
		<div>
            {{ message }}
		</div>
	`,
  data: function () {
    return {
      message: 'Hello Global!'
    }
  }
})

let app = new Vue({
	el: '#app'
})

全域註冊的缺點是,不管有沒有使用到這個元件,其元件一定會載入,會降低網頁速度。

局部註冊(Local Registration)

Component的局部註冊是可以重複使用的,在任一個vue Instance用變數定義,這裡要注意,局部註冊的物件,無法在其他頁面/Instance上被使用,需要在其他葉面在註冊一次。

局部註冊是在vue Instance中,定義components變數在掛載在HTML的元素範圍內。

<div id="app">
	<local-component></local-component>
</div>
let local = {
    template:`
        <div>
            {{ message }}
        </div>
    `,
    data: function () {
        return {
            message: 'Hello Local!'
        }
    }
}

let app= new Vue({
  el: '#app',
  components: {
    'local-component': local
  }
})

Component的data需要是function()

在Vue中,元件被定義成可以重複使用的特性,且每個元件的data是獨立的。
如果data是function時,每次註冊元件都匯回傳新的物件,

全域與局部註冊的差異?

兩者在差在一個是可以在頁面上直接呼叫Component來使用
另一個則是在vue Instance有需要Component的情況下,要用變數來定義。

Resource
Component 操作手法
元件 Components 簡介


上一篇
[Day 10] Computed 計算屬性 Setter/Getter
下一篇
[Day 12] Component Props進的去/Emit出的來
系列文
初探Vue.js 30天30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言