TheRouter
是货拉拉基于HMRouter深度定制的开源路由框架,提供了 Android、iOS、Harmony 三端高一致性使用,在支持平台化应用实现组件化、跨模块调用、动态化等功能的集成等功能基础上,支持动态路由下发、编译时安全检查、路由Path一对多等高度动态能力。
Github: https://github.com/HuolalaTech/hll-wp-therouter-harmony/
官网:http://therouter.cn/
如果你的是新项目,请先记住一点:plugin、router 两个依赖的版本号必须保持一致,请继续往下看接入步骤。
TheRouter 的版本分为两种,稳定版和 rc版,一般不追求新功能我们就用稳定版就行,可以在官网看到最新的版本号和各种版本的说明:https://therouter.cn/docs/2022/09/06/01
在工程根目录命令行引入依赖库和插件库(必须全部依赖,不能只使用其中一个)。
// 引入代码库依赖
ohpm i @hll/therouter
// 引入插件依赖
npm i therouter-plugin
hvigor/hvigor-config.json5
,检查 dependencies
中是否已经加入了依赖,一般为 "therouter-plugin": "x.x.x"
。hvigorfile.ts
文件。plugins
中加入如下对应的依赖// 如果是 hap,则类似如下依赖
import { hapPlugin } from "therouter-plugin";
export default {
plugins: [hapPlugin()]
}
// 如果是 har,则类似如下依赖
import { harPlugin } from "therouter-plugin";
export default {
plugins: [harPlugin()]
}
// 如果是 hap,则类似如下依赖
import { hapPlugin } from "therouter-plugin";
export default {
plugins: [hapPlugin()]
}
oh-package.json5
文件。dependencies
中,是否已经加入了依赖,一般为:"@hll/therouter": "x.x.x"
在项目入口的 UIAbility
的 onCreate()
中加入如下代码:
onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void {
TheRouter.init(this.context);
}
TheRouter 按照华为推荐方案,基于系统 Navigation 实现,所以必须在页面中定义一个容器项 TheRouterPage
,建议创建一个完全新的类作为入口并在 /resources/base/profile/main_pages.json
中配置这个类,复制如下代码:
import { TheRouterPage } from '@hll/therouter';
@Entry
@Component
struct Index {
build() {
RelativeContainer() {
TheRouterPage({
stackId: 'XXXX', //【必传】可以自定义当前stack的名字,每个stack必须唯一
root: 'path' // 【必传】当前应用的首页 path,推荐按照一定格式定义页面path
// 还有很多可选参数,详情请见文档
});
}
.height('100%')
.width('100%')
}
}
给需要跳转的页面加上路由表声明
@Route({path : "http://therouter.com/home"})
export struct HomePage {
xxx
}
在需要跳转页面的位置调用如下代码:
TheRouter
.build("http://therouter.com/home")
.withString('k', 'v') // 向落地页传参数(如果没参数,可不调用)
.with({ hello: 'world' }) // 另一种方式传参
.navigation()
接收有两种形式:
使用注解接收对象时,必须调用 TheRouter.inject(this) 。
// 第一种:使用注解自动填充
// 允许解析成8种基本数据类型或对应封装类
@Autowired()
key1 : string = ''
// 允许自定义传参key,如果不传默认是变量名作为key
@Autowired('hello')
key1 : string = ''
// 使用注解接收对象时,必须调用,建议放在 aboutToApper() 中调用。
TheRouter.inject(this)
// 第二种:通过代码从路由中获取
// 可以在任何方法中调用,getCurrentParam() 返回值是个ESObject
const v = TheRouter.getCurrentParam()['k'];