Aurelia - 自定义元素

Aurelia提供了一种动态添加组件的方法.您可以在应用的不同部分重复使用单个组件,而无需多次包含HTML.在本章中,您将学习如何实现这一目标.

步骤1  - 创建自定义组件

让我们创建新的组件 src 文件夹中的目录.

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 文件,我们需要要求 custom-component.html 才能动态插入.一旦我们这样做,我们就可以添加一个新元素自定义组件.

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自定义元素示例