Edge 组件系统深受 Vue 与 Svelte 等前端框架的启发。它借鉴了 **reusability**、**isolated state**、**props** 和 **slots** 的概念。 请注意,Edge 是一个后端模板引擎,我们不能用 Edge 复制一些前端生态系统原则。它包括。 - **反应性**: 在后端没有反应性的概念。你可以生成 HTML 并通过网络发送它。 - **限定作用域的CSS**: Edge 不是使用 Webpack 这样的前端构建工具来编译的, 因此,它不会为编译和从组件中提取 css 而烦恼。为此,你必须使用现有的前端工具。 ## 创建组件 组件使用常规 Edge 模板文件表示。例如,你可以使用以下标记创建一个名为 `button.edge` 的文件。 ```javascript ``` 然后将其用作其他模板中的组件。 ```javascript @!component('button', { text: 'Login', type: 'submit' }) ``` `@component` 标签总共接受两个参数。一是组件路径(相对于 views 目录),二是组件状态(props)。 > 注:组件不能访问父模板的状态。但是,它们可以访问模板 [globals]() 和 [locals]()。 ## Props props 作为键值对对象的第二个参数传递给组件。通过使用对象属性名,可以在组件文件中直接访问 prop。例如: ```javascript @!component('button', { text: 'Login', type: 'submit' }) ``` 然后 `button` 组件可以访问 `text` 和 `type` 属性,如下所示。 ```javascript ``` ### $props 访问 props 的另一种方法是使用 `$props` 属性。它是 [Props 类](https://github.com/edge-js/edge/blob/develop/src/Component/Props.ts) 的一个实例,并带有一些额外的功能,以使组件编写更容易。 在以下示例中,`serializeExcept` 方法会将所有道具转换为 HTML 属性,但 `text` Prop 除外。 ```javascript ``` ```javascript @!component('button', { text: 'Login', type: 'submit', class: 'py-2 px-8 text-white bg-gray-800', }) ``` 与 `serializeExcept` 方法类似,你可以使用 `serializeOnly` 方法仅序列化选定的道具或使用 `serialize` 方法将所有 Prop 转换为 HTML 属性。 ## 插槽 除了 props,组件还可以接受 `slots`。slots 是父组件可以为其定义标记的命名插槽。 例如,让我们接受 `button` 组件的文本作为插槽而不是 prop。 ```javascript ``` 组件调用者可以如下定义主槽的标记。 ```javascript @component('button', { type: 'submit' }) Login @end ``` ### 主插槽 `@component` 开始和结束标记之间的内容是主插槽的一部分,除非你将其移动到命名插槽中。 `@slot('trigger')` 之外的所有内容都是以下示例中主插槽的一部分。 ```javascript @component('modal') @slot('trigger') Show modal @end
Modal content
@end ``` ### 命名插槽 命名槽允许组件接受多个出口的标记。例如,模态组件可以接受模态标题、正文和操作的标记。 ```javascript // components/modal.edge 文件Are you sure, you want to delete the post
Value of counter is {{ $context.counter.value }}
{{-- Bump the value by one --}} @set($context, 'counter.value', $context.counter.value + 1)Updated value is {{ $context.counter.value }}
@end ``` ## 作为标签的组件 Edge 允许你将存储在 `./resources/views/components` 目录中的组件作为 Edge 标签引用。 在 `resources/views/components/button.edge` 文件中创建以下模板。 ```javascript // 文件名: resources/views/components/button.edge ``` 现在,除了使用 `@component` 标记来引用按钮组件,你也可以将其引用为 `@button` 标签。 ```javascript @!button({ type: 'primary', text: 'Login' }) ``` 你可以使用点符号引用嵌套目录中的组件。例如, `./components/form/input.edge` 中存储的文件引用如下: ```javascript @!form.input({ type: 'text', placeholder: 'Enter username' }) ``` 以下是一个对照表,用于了解应用于组件路径以计算标签名称的转换。 | 模板路径 | 标签名 | |---------------|-----------| | form/input.edge | `@form.input` | | tool_tip.edge | `@toolTip` | | checkout_form/input.edge | `@checkoutForm.input` |