组件()函数,把它们设为a美元的产品财产。但是,让我们允许组件执行查询的工作。

怎么做?组件是服务,这意味着自动装配工作正常。这个例子假设你有一个产品理论实体和ProductRepository

12 3 4 5 6 7 8 9 10 11 12 13 14 16 17 18 19 20 21 22
/ / src /组件/ FeaturedProductsComponent.php名称空间应用程序组件使用应用程序存储库ProductRepository使用ob娱乐下载用户体验TwigComponent属性AsTwigComponent# (AsTwigComponent (featured_products)]FeaturedProductsComponent私人ProductRepositoryproductRepository公共函数__construct(ProductRepositoryproductRepository->productRepository =productRepository;}公共函数getProducts()数组//返回product数组的示例方法返回->productRepository->findFeatured ();}}

在模板中getProducts ()方法可以通过this.products

1 2 3 4 5 6 7 8 9
{/组件/ featured_products.html #模板。树枝#}<div><h3>主打产品h3>{%积在这里。产品%}...{%endfor%}div>

因为这个组件没有任何我们需要填充的公共属性,你可以用:

1
{{component('featured_products')}}

请注意

因为组件是服务,所以可以使用正常的依赖注入。但是,每个组件服务都注册到共享:假.这意味着您可以使用不同的数据安全地多次呈现相同的组件,因为每个组件都是一个独立的实例。

在前面的例子中,不是立即查询特色产品(例如在__construct ()),我们创建了一个getProducts ()方法,并从模板via中调用this.products

这样做是因为,作为一般规则,您应该使您的组件懒惰的尽可能只存储您需要的关于其属性的信息(这也有助于您将组件转换为住组件后)。在此设置中,查询仅在getProducts ()方法实际被调用。这与框架中的“计算属性”非常相似Vue

但是没有魔法getProducts ()方法:如果你打电话this.products在模板中多次,查询将被多次执行。

让你的getProducts ()方法的行为类似于真正的计算属性,调用computed.products在模板中。计算是一个代理,它包装组件并缓存方法的返回。如果它们被调用额外的次数,则使用缓存的值。

12 3 4 5 6 7 8 9 10 11 12 13 14
{/组件/ featured_products.html #模板。树枝#}<div><h3>主打产品h3>{%积在计算中。产品%}...{%endfor%}...{%积在计算中。产品%}{#使用缓存,不会导致第二次查询#}...{%endfor%}div>

请注意

计算方法只适用于没有必需参数的组件方法。

组件的一个常见需求是为根节点配置/呈现属性。属性是传递给的任何数据组件()不能挂载到组件本身上。这些额外的数据被添加到ComponentAttributes可通过以下方式获取属性在组件的模板中。

要在组件的模板中使用属性根元素中的变量:

1 2 3 4 5
{/组件/ my_component.html #模板。树枝#}<div{{attributes}}>我的组件!div>

当呈现组件时,你可以传递一个html属性数组来添加:

1 2 3 4 5 6
{{component('my_component', {class: 'foo', style: 'color:red'})}}{#渲染为:#}<div“foo”风格“颜色:红”>我的组件!div>

将属性的值设置为在呈现时排除该值:

1 2 3 4 5 6 7 8
{/组件/ my_component.html #模板。树枝#}<输入{{属性}}/>{#渲染组件#}{{component('my_component', {type: 'text', value: ", autofocus: null})}}{#渲染为:#}<输入类型“文本”价值""自动对焦/>

add ()方法在TwigComponents 2.7中引入。

向根组件元素中添加一个自定义的Stimulus控制器:

1
<div{{属性。add(刺激性控制器('my-controller', {someValue: 'foo'}))}}>

请注意

你可以调整模板中暴露的属性变量:

1 2 3 4 5
#[AsTwigComponent('alert', attributesVar: '_attributes')]AlertComponent/ /……