maomi
Introduction
Guide
Documents

Using Components

Using component in component

Components in maomi are low-cost abstractions. Some web frameworks have a significant overhead with components, but maomi only has a little. Sometimes components can help improve performance.

Like DOM elements, a component can be used as tags.

#[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(),
}
}
}

Slots in components

The component can put a "<slot />" tag in the template. It will be replaced with the child nodes in its users.

#[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(),
}
}
}

It is able to pass data in the slot with "data" attribute. Its users can retrieve the reference of the data with "slot:xxx" attributes.

Besides it, the slot data type should be specified with the "SlotData" attribute argument.

#[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(),
}
}
}