条件渲染
2026/5/15大约 1 分钟euvuirustwasmusage-introductionconditional
if 条件渲染
let show_details: Signal<bool> = use_signal(|| false);
html! {
primary_button {
label: "Toggle"
onclick: use_toggle(show_details)
"Toggle"
}
if {show_details.get()} {
div {
"Details visible"
}
} else {
""
}
}注意
if 表达式的 else 分支不能省略,空内容请使用 ""。
else if 链
html! {
if {score.get() >= 90} {
div { "Excellent" }
} else if {score.get() >= 60} {
div { "Pass" }
} else {
div { "Fail" }
}
}match 条件渲染
let user_type: Signal<String> = use_signal(|| "guest".to_string());
html! {
match {user_type.get().as_str()} {
"guest" => {
div { "Welcome, guest!" }
}
"user" => {
div { "Hello, user!" }
}
_ => {
div { "Welcome, administrator!" }
}
}
}提示
match 必须包含 _ 通配分支,否则编译不通过。
属性值条件渲染
if 条件渲染不仅可用于子节点位置,还可在属性值中使用,实现响应式的属性切换:
let is_active: Signal<bool> = use_signal(|| false);
html! {
div {
class: if { is_active.get() } { c_active() } else { c_inactive() }
"Content"
}
}样式中同样支持条件渲染:
html! {
div {
style: {
color: if { is_active.get() } { "#4f46e5".to_string() } else { "inherit".to_string() };
border_bottom: if { is_active.get() } { "2px solid #4f46e5".to_string() } else { "2px solid transparent".to_string() };
}
"Tab item"
}
}提示
属性值中的 if 条件会自动包装为响应式 Signal<String>,信号变化时属性值自动更新,无需手动订阅。
Tab 切换示例
结合 match 和属性值条件渲染实现 Tab 切换:
let tab: Signal<String> = use_signal(|| "info".to_string());
html! {
div {
div {
class: c_tab_bar()
div {
class: if { tab.get() == "info" } { c_tab_item_active() } else { c_tab_item_inactive() }
onclick: move |_event: Event| { tab.set("info".to_string()); }
"Info"
}
div {
class: if { tab.get() == "settings" } { c_tab_item_active() } else { c_tab_item_inactive() }
onclick: move |_event: Event| { tab.set("settings".to_string()); }
"Settings"
}
}
match { tab.get().as_str() } {
"info" => {
div { "Information content" }
}
_ => {
div { "Settings content" }
}
}
}
}