1
0

example.rs 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. use dioxus::prelude::*;
  2. use dioxus_router::prelude::*;
  3. fn main() {
  4. dioxus_web::launch(App);
  5. }
  6. fn App(cx: Scope) -> Element {
  7. let routes = use_segment(&cx, || {
  8. Segment::default()
  9. .index(Home as Component)
  10. .fixed(
  11. "blog",
  12. Route::new(Blog as Component).nested(
  13. Segment::default().index(BlogList as Component).catch_all(
  14. ParameterRoute::new("post_id", BlogPost as Component).name(BlogPost),
  15. ),
  16. ),
  17. )
  18. .fixed("myblog", "/blog")
  19. .fallback(PageNotFound as Component)
  20. });
  21. cx.render(rsx! {
  22. Router {
  23. routes: routes.clone(),
  24. NavBar {}
  25. Outlet {}
  26. }
  27. })
  28. }
  29. fn NavBar(cx: Scope) -> Element {
  30. cx.render(rsx! {
  31. nav {
  32. ul {
  33. li { Link { target: (RootIndex, []), "Home" } }
  34. li { Link { target: "/blog", "Blog" } }
  35. }
  36. }
  37. })
  38. }
  39. fn Home(cx: Scope) -> Element {
  40. cx.render(rsx! {
  41. h1 { "Welcome to the Dioxus Blog!" }
  42. })
  43. }
  44. fn Blog(cx: Scope) -> Element {
  45. cx.render(rsx! {
  46. h1 { "Blog" }
  47. Outlet {}
  48. })
  49. }
  50. fn BlogList(cx: Scope) -> Element {
  51. cx.render(rsx! {
  52. h2 { "Choose a post" }
  53. ul {
  54. li { Link {
  55. target: (BlogPost, [("post_id", String::from("1"))]),
  56. "Read the first blog post"
  57. } }
  58. li { Link {
  59. target: (BlogPost, [("post_id", String::from("2"))]),
  60. "Read the second blog post"
  61. } }
  62. }
  63. })
  64. }
  65. fn BlogPost(cx: Scope) -> Element {
  66. let route = use_route(&cx).unwrap();
  67. let post_id = route.parameters.get("post_id");
  68. let post = post_id
  69. .map(|id| id.to_string())
  70. .unwrap_or(String::from("unknown"));
  71. cx.render(rsx! {
  72. h2 { "Blog Post: {post}"}
  73. })
  74. }
  75. fn PageNotFound(cx: Scope) -> Element {
  76. cx.render(rsx! {
  77. h1 { "Page not found" }
  78. p { "We are terribly sorry, but the page you requested doesn't exist." }
  79. })
  80. }