DAY11 | 跟 Vue.js 認識的30天 - Vue 的模組註冊(`Component Registration`)
模組的命名
一個模組的命名關係到我們是否能快速地知道這個模組的功能是甚麼,同時可以避免跟現有的 HTML 標籤相衝突。
在Vue.js - 风格指南中, component 有一個重要的命名規則 - Multi-word component names ,指的是模組的命名需要由多個單字組合而成,這是為了避免跟現有的 HTML 標籤產生衝突(現有的 HTML 標籤都是一個單字)。
命名方法有2種:
使用 kebab-case (短橫線分隔):如
my-component-name、todo-item、cart-item等。使用 PascalCase (首字母大寫):
MyComponentName、TodoItem、CartItem等。
必須注意的是在 HTML 時,標籤名一定要是 kebab-case (短橫線分隔)模式,例如: <my-component-name></my-component-name> 、 <todo-item></todo-item>。
更多命名的規則請參考Vue.js - 风格指南。
模組的註冊
全域註冊
在上一篇文章中所介紹的模組都是用全域註冊。沒錯,就是使用 Vue.component('模組名',{...}) ,模組全域註冊的目的是讓其他的模組都能使用它。
模組的全域註冊
1  | Vue.component('global-component-a',{  | 
全域註冊模組的使用
1  | <div id="vm">  | 
通過上方可知,只要是全域的模組,其他的模組都可以直接使用而不用再次註冊。
在 Vue 文件中有提到
Remember that global registration must take place before the root Vue instance is created (with new Vue).
全域模組註冊必須要在根 Vue 實例創建前。(根 Vue 實例就是用 new Vue 創建出來的那個)。
區域註冊
模組的區域註冊*
1  | const LocalComponentA = {  | 
區域註冊模組的使用
1  | <div id="vm">  | 
這裡有幾個需要注意的地方:
模組區域註冊必須先宣告賦值後才能使用,像是不能在
LocalComponentA中註冊使用LocalComponentB,因為LocalComponentB的宣告賦值是在LocalComponentA之後的。要使用區域模組一定要先註冊,像是在
LocalComponentB中要使用LocalComponentA,就必須在LocalComponentB的 options 中加入components:{LocalComponentA:LocalComponentA},使用 ES6 語法可寫成components:{LocalComponentA},這時在LocalComponentB中才可以使用LocalComponentA。
Demo:
See the Pen [DAY11]跟 Vue.js 認識的30天 - Vue 的模組註冊 by Celeste6666 (@celeste6666) on CodePen.
參考資料:
