# vue 註冊元件的手法 ## 元件 header、footer、sidebar 都會很常重複使用,content 是會變化的,用不同元件來插入。網頁最外層就是根元件,也就是createApp 建立的元件,稱為「根元件」。 ## 註冊元件 元件註冊分為兩種:「全域註冊」和「區域註冊」。 ### 全域註冊 ```javascript= const app = Vue.createApp({ data() { return { text: '外部元件文字' }; }, }); app.component("alert", { data() { return { text: '內部文字' }; }, template: `<div class="alert alert-primary" role="alert"> {{ text }} </div>` }); app.mount("#app"); ``` 元件上的名稱可作為標籤的名稱,即可渲染至畫面上 ```htmlembedded= <alert></alert> ``` * 全域註冊的子元件的撰寫順序要在根元件後面 * 元件可以重複使用 (例如:好幾個 alert) * 雖然可以但不建議 .component 直接串接在 createApp 後,這樣不好閱讀。 * template 仍符合關注點分離,裡面的標籤只是「樣板」 * ### 區域註冊 元件程式碼要先註冊在其中一個區塊內,只有在該區塊中才能使用,其他不行。 ```javascript= const content = { data() { return { text: '這是 content 子元件' } }, template: `<div class="content">{{ text }}</div>` } const app = createApp({ data() { return { text: '123' } }, components: { content, } }) ``` ### 模組化 把元件獨立成一個檔案,透過 ESModule 的方式,來進行匯入。 ```jsx= export default { data() { return { text: '外部匯入的元件' } }, template: `<div class="alert alert-primary" role="alert"> {{ text }} </div>` } ``` ```jsx= import alert4 from './component-alert.js' const app = Vue.createApp({ data() { return { text: '外部元件文字' } }, components: { alert4 } }); app.mount("#app");S ```  ### 參考資料+圖片來源 - [六角 2022 Vue 直播班](https://www.hexschool.com/courses/vue-training.html) ###### tags: `Vue` `六角 2022 Vue 直播班` `元件`
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up