maomi
介绍
入门
文档

使用组件

在组件中使用组件

maomi 的组件是低开销抽象。一些其他 web 框架中的组件是高开销的,但 maomi 只有一点点开销。有时,使用组件还可以提升性能。

像 DOM 节点一样,组件可以作为标签使用。

#[component(Backend = DomBackend)]
struct MyChild {
template: template! {
<div> "This line is in the child component." </div>
}
}
impl Component for MyChild {
fn new() -> Self {
Self {
template: Default::default(),
}
}
}
#[component(Backend = DomBackend)]
struct MyWebsite {
template: template! {
<MyChild />
}
}
impl Component for MyWebsite {
fn new() -> Self {
Self {
template: Default::default(),
}
}
}

组件的 slot

组件可以在模板中放置 <slot /> 标签。它会被组件使用者中的子节点代替。

#[component(Backend = DomBackend)]
struct MyChild {
template: template! {
<div> "This line is in the child component." </div>
<slot />
}
}
impl Component for MyChild {
fn new() -> Self {
Self {
template: Default::default(),
}
}
}
#[component(Backend = DomBackend)]
struct MyWebsite {
template: template! {
<MyChild>
<div> "This line will be placed in the slot." </div>
</_>
}
}
impl Component for MyWebsite {
fn new() -> Self {
Self {
template: Default::default(),
}
}
}

也可以通过 slot 传递数据。组件使用者可以通过 slot:xxx 来获得这些数据。

同时, slot 的数据类型需要在 SlotData 组件属性中定义。

#[component(Backend = DomBackend, SlotData = String)]
struct MyChild {
template: template! {
<div> "This line is in the child component." </div>
<slot data=&{ self.my_string_data } />
},
my_string_data: String,
}
impl Component for MyChild {
fn new() -> Self {
Self {
template: Default::default(),
my_string_data: "slot data".to_string(),
}
}
}
#[component(Backend = DomBackend)]
struct MyWebsite {
template: template! {
<MyChild slot:sd>
<div> { sd } </div>
</_>
}
}
impl Component for MyWebsite {
fn new() -> Self {
Self {
template: Default::default(),
}
}
}