dioxus/examples/counter.rs

54 lines
1.4 KiB
Rust
Raw Normal View History

2023-04-09 20:42:40 +00:00
//! Comparison example with leptos' counter example
//! https://github.com/leptos-rs/leptos/blob/main/examples/counters/src/lib.rs
use dioxus::prelude::*;
fn main() {
launch(app);
2023-04-09 20:42:40 +00:00
}
fn app() -> Element {
let mut counters = use_signal(|| vec![0, 0, 0]);
2024-01-21 07:32:12 +00:00
let sum = use_memo(move || counters.read().iter().copied().sum::<i32>());
2023-04-09 20:42:40 +00:00
2024-01-16 19:18:46 +00:00
rsx! {
2023-04-09 20:42:40 +00:00
div {
2024-01-15 21:06:05 +00:00
button { onclick: move |_| counters.write().push(0), "Add counter" }
button {
onclick: move |_| {
counters.write().pop();
},
"Remove counter"
}
2023-04-09 20:42:40 +00:00
p { "Total: {sum}" }
for i in 0..counters.len() {
Child { i, counters }
}
}
}
}
#[component]
2024-01-21 20:46:19 +00:00
fn Child(counters: Signal<Vec<i32>>, i: usize) -> Element {
rsx! {
li {
button { onclick: move |_| counters.write()[i] -= 1, "-1" }
input {
value: "{counters.read()[i]}",
oninput: move |e| {
2024-01-18 11:03:17 +00:00
if let Ok(value) = e.value().parse::<i32>() {
counters.write()[i] = value;
2023-04-09 20:42:40 +00:00
}
}
}
button { onclick: move |_| counters.write()[i] += 1, "+1" }
button {
onclick: move |_| {
counters.write().remove(i);
},
"x"
}
2023-04-09 20:42:40 +00:00
}
}
}