路由
2026/5/15小于 1 分钟euvuirustwasmexamplerouter
获取当前路由
pub fn current_route() -> String {
let window: Window = window().expect("no global window exists");
let hash: String = window.location().hash().unwrap_or_default();
let route: String = hash.strip_prefix('#').unwrap_or(&hash).to_string();
if route.is_empty() {
"/".to_string()
} else {
route
}
}导航
pub fn navigate(route: &str) {
let window: Window = window().expect("no global window exists");
let location: Location = window.location();
let new_hash: String = format!("#{}", route);
let _ = location.set_hash(&new_hash);
}创建导航链接
pub fn link_handler(route: String) -> NativeEventHandler {
NativeEventHandler::create("click", move |_event: Event| {
navigate(&route);
})
}使用:
html! {
a {
onclick: link_handler("/about".to_string())
"Go to About"
}
}检测移动端
pub fn is_mobile() -> bool {
let window: Window = window().expect("no global window exists");
let width: f64 = window
.inner_width()
.ok()
.map(|value: JsValue| Number::from(value).value_of())
.unwrap_or(0.0);
width < 768.0
}提示
is_mobile() 通过 window.inner_width() 获取视口宽度,判断是否为移动设备(宽度 < 768px),可用于响应式布局条件渲染。
路由匹配
let route_signal: Signal<String> = use_signal(current_route);
use_window_event("hashchange", move || {
let new_route: String = current_route();
route_signal.set(new_route);
});
html! {
main {
match {route_signal.get().as_str()} {
"/" => { page_home() }
"/list" => { page_list() }
_ => { page_not_found() }
}
}
}提示
euv 示例使用 hash 路由(#/path),修改 window.location.hash 即可切换页面。使用 use_window_event("hashchange", ...) 监听路由变化,Hook 上下文清除时自动移除监听器,无需手动清理。