counter.rs 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. //! Comparison example with leptos' counter example
  2. //! https://github.com/leptos-rs/leptos/blob/main/examples/counters/src/lib.rs
  3. use dioxus::prelude::*;
  4. fn main() {
  5. launch(app);
  6. }
  7. fn app() -> Element {
  8. let mut counters = use_signal(|| vec![0, 0, 0]);
  9. let sum = use_memo(move || counters.read().iter().copied().sum::<i32>());
  10. rsx! {
  11. div {
  12. button { onclick: move |_| counters.write().push(0), "Add counter" }
  13. button {
  14. onclick: move |_| {
  15. counters.write().pop();
  16. },
  17. "Remove counter"
  18. }
  19. p { "Total: {sum}" }
  20. for i in 0..counters.len() {
  21. Child { i, counters }
  22. }
  23. }
  24. }
  25. }
  26. #[component]
  27. fn Child(counters: Signal<Vec<i32>>, i: usize) -> Element {
  28. rsx! {
  29. li {
  30. button { onclick: move |_| counters.write()[i] -= 1, "-1" }
  31. input {
  32. value: "{counters.read()[i]}",
  33. oninput: move |e| {
  34. if let Ok(value) = e.value().parse::<i32>() {
  35. counters.write()[i] = value;
  36. }
  37. }
  38. }
  39. button { onclick: move |_| counters.write()[i] += 1, "+1" }
  40. button {
  41. onclick: move |_| {
  42. counters.write().remove(i);
  43. },
  44. "x"
  45. }
  46. }
  47. }
  48. }