###### tags: `Vue` # 【Vue】元件註冊 >元件必須要**註冊**後才能使用,註冊方式分為「全域( global )」以及「區域( local )」 ## 全域註冊 >註冊後整個 app 都可以使用 * 使用 app.component() 來註冊 * 在 SFC 中要使用 import ```js= import MyComponent from './App.vue' app.component('MyComponent', MyComponent) ``` * 也可以一次註冊很多個 ```js= app .component('ComponentA', ComponentA) .component('ComponentB', ComponentB) .component('ComponentC', ComponentC) ``` * 註冊完之後就可以在模板中使用 ```html= <!-- this will work in any component inside the app --> <ComponentA/> <ComponentB/> <ComponentC/> ``` ### 全域註冊的缺點 * 全域註冊不會移除沒有使用到的 component ([tree-shaking](https://ithelp.ithome.com.tw/articles/10274978)) * 使用全域註冊會看不太出來 component 之間的關係,可能會找不到子元件的位置,在大型專案的維護上較為困難。 ## 區域註冊 >只有在註冊過的父元件中才可以使用 - tree-shaking freindly * 使用 import 來註冊 ```html= <script setup> import ComponentA from './ComponentA.vue' </script> <template> <ComponentA /> </template> ``` * 不是 SFC 的情況 ```js= import ComponentA from './ComponentA.js' export default { components: { ComponentA: ComponentA }, setup() { // ... } } ``` * componet 的名字註冊可以使用 ES2015 的語法糖 ```js= export default { components: { ComponentA } // ... } ``` ## 元件命名 上面的示範都是使用駝峰式命名( PascalCase ),有幾個原因: 1. 駝峰式命名是合法的 JS Identifiler,在引入和註冊元件時會比較方便,有些 IDE 也回提供自動完成 2. 用來區分一般的 html tag 與 元件的 tag :::warning 駝峰式命名只能用在 SFC 中,因為一般 html tag 是無法區分大小寫的 ::: * Vue 也支援 kebab-case 命名法,所以元件可以寫成 `<MyComponent/>` 或是 `<my-component/>`