Custom Elements
优质
小牛编辑
143浏览
2023-12-01
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创建简单的组件。 它将用于在屏幕上呈现header和footer文本。
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>
以下是输出。 Header和Footer文本是从app.js myComponent呈现的。 附加文本从custom-component.js呈现。
