Aurelia - 自定義元素



Aurelia 提供了一種動態新增元件的方式。你可以在應用程式的不同部分重複使用單個元件,而無需多次包含 HTML。在本教程中,你將學習如何實現此目的。

步驟 1 - 建立自定義元件

讓我們在 src 資料夾中建立一個新的 components 資料夾。

C:\Users\username\Desktop\aureliaApp\src>mkdir components

在此資料夾中,我們將建立 custom-component.html。此元件將稍後插入 HTML 頁面。

custom-component.html

<template>
   <p>This is some text from dynamic component...</p>
</template>

步驟 2 - 建立主元件

我們將在 app.js 中建立簡單元件。它將用於在螢幕上呈現 頁首頁尾 文字。

app.js

export class MyComponent {
   header = "This is Header";
   content = "This is content";
}

步驟 3 - 新增自定義元件

在我們 app.html 檔案中,我們需要 require custom-component.html 才能動態插入它。完成此操作後,我們可以新增一個新元素 custom-component

app.html

<template>
   <require from = "./components/custom-component.html"></require>

   <h1>${header}</h1>
   <p>${content}</p>
   <custom-component></custom-component>
</template>

以下是輸出。頁首頁尾 文字從 app.js 中的 myComponent 中呈現。其他文字從 custom-component.js 中呈現。

Aurelia Custom Elements Example
廣告
© . All rights reserved.