Try   HackMD

vue 註冊元件的手法

元件

header、footer、sidebar 都會很常重複使用,content 是會變化的,用不同元件來插入。網頁最外層就是根元件,也就是createApp 建立的元件,稱為「根元件」。

註冊元件

元件註冊分為兩種:「全域註冊」和「區域註冊」。

全域註冊

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");

元件上的名稱可作為標籤的名稱,即可渲染至畫面上

<alert></alert>
  • 全域註冊的子元件的撰寫順序要在根元件後面
  • 元件可以重複使用 (例如:好幾個 alert)
  • 雖然可以但不建議 .component 直接串接在 createApp 後,這樣不好閱讀。
  • template 仍符合關注點分離,裡面的標籤只是「樣板」

區域註冊

元件程式碼要先註冊在其中一個區塊內,只有在該區塊中才能使用,其他不行。

const content = { data() { return { text: '這是 content 子元件' } }, template: `<div class="content">{{ text }}</div>` } const app = createApp({ data() { return { text: '123' } }, components: { content, } })

模組化

把元件獨立成一個檔案,透過 ESModule 的方式,來進行匯入。

export default { data() { return { text: '外部匯入的元件' } }, template: `<div class="alert alert-primary" role="alert"> {{ text }} </div>` }
import alert4 from './component-alert.js' const app = Vue.createApp({ data() { return { text: '外部元件文字' } }, components: { alert4 } }); app.mount("#app");S

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

參考資料+圖片來源

tags: Vue 六角 2022 Vue 直播班 元件