make Leptos iteration example equivalent of Dioxus iteration example (#2191)

This commit is contained in:
Greg Johnston authored and GitHub committed 2024-03-30 03:52:32 -07:00
1 parent 9f280a8d84
commit d77e1eb3ed
1 file changed
+11 -44
+11 -44
View File
@@ -270,61 +270,28 @@ fn Counters() -> Element {
} }
``` ```
[While in Leptos, you would need to track keys, use the `<For>` component, create new signals, and manually clean up memory](https://book.leptos.dev/view/04_iteration.html#dynamic-rendering-with-the-for-component): [While in Leptos you would use the `<For>` component.](https://book.leptos.dev/view/04_iteration.html#dynamic-rendering-with-the-for-component):
```rust ```rust
fn Counters() -> Element { fn Counters() -> Element {
let initial_counters = (0..initial_length) let counters = RwSignal::new(vec![0; 10]);
.map(|id| (id, create_signal(id + 1)))
.collect::<Vec<_>>();
let (counters, set_counters) = create_signal(initial_counters);
let add_counter = move |_| {
let sig = create_signal(next_counter_id + 1);
set_counters.update(move |counters| counters.push((next_counter_id, sig)));
next_counter_id += 1;
};
view! { view! {
<div> <button on:click=move |_| counters.update(|n| n.push(n.len()))>"Add Counter"</button>
<button on:click=add_counter>
"Add Counter"
</button>
<ul>
<For <For
each=counters each=move || 0..counters.with(Vec::len)
key=|counter| counter.0 key=|idx| *idx
children=move |(id, (count, set_count))| { let:idx
view! { >
<li> <li>
<button <button on:click=move |_| counters.update(|n| n[idx] += 1)>
on:click=move |_| set_count.update(|n| *n += 1) {Memo::new(move |_| counters.with(|n| n[idx]))}
>
{count}
</button> </button>
<button <button on:click=move |_| counters.update(|n| { n.remove(idx); })>
on:click=move |_| {
set_counters.update(|counters| {
counters.retain(|(counter_id, (signal, _))| {
if counter_id == &id {
signal.dispose();
}
counter_id != &id
})
});
}
>
"Remove" "Remove"
</button> </button>
</li> </li>
} </For>
}
/>
</ul>
</div>
}
} }
``` ```