counters.rs 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. //! A simple counters example that stores a list of items in a vec and then iterates over them.
  2. use dioxus::prelude::*;
  3. const STYLE: Asset = asset!("/examples/assets/counter.css");
  4. fn main() {
  5. dioxus::launch(app);
  6. }
  7. fn app() -> Element {
  8. // Store the counters in a signal
  9. let mut counters = use_signal(|| vec![0, 0, 0]);
  10. // Whenever the counters change, sum them up
  11. let sum = use_memo(move || counters.read().iter().copied().sum::<i32>());
  12. rsx! {
  13. document::Link { rel: "stylesheet", href: STYLE }
  14. div { id: "controls",
  15. button { onclick: move |_| counters.write().push(0), "Add counter" }
  16. button { onclick: move |_| { counters.write().pop(); }, "Remove counter" }
  17. }
  18. h3 { "Total: {sum}" }
  19. // Calling `iter` on a Signal<Vec<>> gives you a GenerationalRef to each entry in the vec
  20. // We enumerate to get the idx of each counter, which we use later to modify the vec
  21. for (i, counter) in counters.iter().enumerate() {
  22. // We need a key to uniquely identify each counter. You really shouldn't be using the index, so we're using
  23. // the counter value itself.
  24. //
  25. // If we used the index, and a counter is removed, dioxus would need to re-write the contents of all following
  26. // counters instead of simply removing the one that was removed
  27. //
  28. // You should use a stable identifier for the key, like a unique id or the value of the counter itself
  29. li { key: "{i}",
  30. button { onclick: move |_| counters.write()[i] -= 1, "-1" }
  31. input {
  32. r#type: "number",
  33. value: "{counter}",
  34. oninput: move |e| {
  35. if let Ok(value) = e.parsed() {
  36. counters.write()[i] = value;
  37. }
  38. }
  39. }
  40. button { onclick: move |_| counters.write()[i] += 1, "+1" }
  41. button { onclick: move |_| { counters.write().remove(i); }, "x" }
  42. }
  43. }
  44. }
  45. }