1、路由跳转
创建测试页面OnePage
import { HMRouter } from "@hadss/hmrouter";@HMRouter({pageUrl: "OnePage",
})
@Component
export struct OnePage {build() {Column() {Text("测试页面 - OnePage").fontSize(30).fontWeight(FontWeight.Bold)}}
}
首页添加页面跳转按钮
// 跳转按钮 - OnePageButton("跳转到 - OnePage").onClick((event: ClickEvent) => {HMRouterMgr.push({pageUrl: "OnePage",param: {name: "张三",age: 18}})})
跳转方法参数说明
HMRouterMgr.push({navigationId?: string; // 指定导航HMNavigation的navigationIdpageUrl?: string; // push到哪个页面param?: ESObject; // 传参对象interceptors?: IHMInterceptor[]; // 指定路由拦截器animator?: IHMAnimator | boolean; // 指定跳转动画skipAllInterceptor?: boolean; // 是否跳过路由拦截
})
2、参数接收
在OnePage页面 通过getCurrentParam获取当前路由
@State param: HMPageParam = HMRouterMgr.getCurrentParam(HMParamType.all) as HMPageParamaboutToAppear(): void {console.log("OnePage aboutToAppear" + JSON.stringify(this.param))}
3、路由拦截器
创建拦截器目录及OnePage拦截器 ,拦截器需要实现IHMInterceptor接口并通过@HMInterceptor注解添加拦截器信息。
@HMInterceptor注解参数说明
IHMInterceptor接口需要实现handle方法。handle方法参数可以获取路由信息,方法返回值必须是一个HMInterceptorAction枚举。
import { HMInterceptor, HMInterceptorAction, HMInterceptorInfo,HMRouterPathInfo,IHMInterceptor } from '@hadss/hmrouter';@HMInterceptor({ interceptorName: "OnePageInterceptor" })
export class OnePageInterceptor implements IHMInterceptor {handle(info: HMInterceptorInfo): HMInterceptorAction {const routerPathInfo: HMRouterPathInfo = info.routerPathInfo;// 如果是张三 停止跳转if(routerPathInfo.param?.name === "张三") {console.log("OnePageInterceptor - 张三 停止跳转")return HMInterceptorAction.DO_REJECT;}else {// 继续向下执行console.log("OnePageInterceptor - 继续向下执行")return HMInterceptorAction.DO_NEXT}}
}
在OnePage页面使用拦截器
@HMRouter({pageUrl: "OnePage",interceptors: ["OnePageInterceptor"]
})