1
0

dynamic_route.rs 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115
  1. #![allow(non_snake_case)]
  2. use dioxus::prelude::*;
  3. use dioxus_router::prelude::*;
  4. fn main() {
  5. #[cfg(target_arch = "wasm32")]
  6. dioxus_web::launch(App);
  7. #[cfg(not(target_arch = "wasm32"))]
  8. dioxus_desktop::launch(App);
  9. }
  10. // ANCHOR: router
  11. #[derive(Routable, Clone)]
  12. #[rustfmt::skip]
  13. enum Route {
  14. #[layout(NavBar)]
  15. #[route("/")]
  16. Home {},
  17. #[nest("/blog")]
  18. #[layout(Blog)]
  19. #[route("/")]
  20. BlogList {},
  21. #[route("/blog/:name")]
  22. BlogPost { name: String },
  23. #[end_layout]
  24. #[end_nest]
  25. #[end_layout]
  26. #[route("/:..route")]
  27. PageNotFound {
  28. route: Vec<String>,
  29. },
  30. }
  31. // ANCHOR_END: router
  32. fn App(cx: Scope) -> Element {
  33. render! {
  34. Router {}
  35. }
  36. }
  37. #[inline_props]
  38. fn NavBar(cx: Scope) -> Element {
  39. render! {
  40. nav {
  41. ul {
  42. li { Link { target: Route::Home {}, "Home" } }
  43. li { Link { target: Route::BlogList {}, "Blog" } }
  44. }
  45. }
  46. Outlet {}
  47. }
  48. }
  49. #[inline_props]
  50. fn Home(cx: Scope) -> Element {
  51. render! {
  52. h1 { "Welcome to the Dioxus Blog!" }
  53. }
  54. }
  55. // ANCHOR: blog
  56. #[inline_props]
  57. fn Blog(cx: Scope) -> Element {
  58. render! {
  59. h1 { "Blog" }
  60. Outlet {}
  61. }
  62. }
  63. // ANCHOR_END: blog
  64. // ANCHOR: blog_list
  65. #[inline_props]
  66. fn BlogList(cx: Scope) -> Element {
  67. render! {
  68. h2 { "Choose a post" }
  69. ul {
  70. li {
  71. Link {
  72. target: Route::BlogPost { name: "Blog post 1".into() },
  73. "Read the first blog post"
  74. }
  75. }
  76. li {
  77. Link {
  78. target: Route::BlogPost { name: "Blog post 2".into() },
  79. "Read the second blog post"
  80. }
  81. }
  82. }
  83. }
  84. }
  85. // ANCHOR_END: blog_list
  86. // ANCHOR: blog_post
  87. // The name prop comes from the /:name route segment
  88. #[inline_props]
  89. fn BlogPost(cx: Scope, name: String) -> Element {
  90. render! {
  91. h2 { "Blog Post: {name}"}
  92. }
  93. }
  94. // ANCHOR_END: blog_post
  95. #[inline_props]
  96. fn PageNotFound(cx: Scope, route: Vec<String>) -> Element {
  97. render! {
  98. h1 { "Page not found" }
  99. p { "We are terribly sorry, but the page you requested doesn't exist." }
  100. pre {
  101. color: "red",
  102. "log:\nattemped to navigate to: {route:?}"
  103. }
  104. }
  105. }