HMrouter
HMRouter作为应用内页面跳转场景解决方案,为开发者提供了功能完备、高效易用的路由框架。
HMRouter底层对系统Navigation进行封装,集成了Navigation、NavDestination、NavPathStack的系统能力,提供了可复用的路由拦截、页面生命周期、自定义转场动画,并且在跳转传参、额外的生命周期、服务型路由方面对系统能力进行了扩展,同时开发者可以高效的将历史代码中的Navigation组件接入到HMRouter框架中。
目的是让开发者在开发过程中减少模板代码,降低拦截器、自定义转场动画、组件感知页面生命周期等高频开发场景的实现复杂度,帮助开发者更好的实现路由与业务模块间的解耦。
安装
在DevEco Studio
终端中使用命令(ohpm命令集成在终端,如果想要在全局都使用,得去DevEco Studio
安装目录寻找ohpm的地址并配置path)。
bash
ohpm install @hadss/hmrouter
在根目录下的hvigor/hvigor-config.json文件中添加, 注意这里@hadss/hmrouter-plugin的版本需要和@hadss/hmrouter的版本一致
json
"dependencies": {
"@hadss/hmrouter-plugin": "^1.1.0-beta.0"
},
找到entry/hvigorfile.ts 文件,添加
ts
import { hapTasks } from '@ohos/hvigor-ohos-plugin';
import { hapPlugin } from '@hadss/hmrouter-plugin';
export default {
system: hapTasks,
plugins: [hapPlugin()]
}
在onCreate
事件中初始化
kotlin
HMRouterMgr.openLog('INFO');
HMRouterMgr.init({
context: this.context,
});
使用HMNavigation
定义入口(类似于vue
的router-view
)
scala
// page/Index.ets
import { HMDefaultGlobalAnimator, HMNavigation, HMRouterMgr } from '@hadss/hmrouter';
import { AttributeUpdater } from '@kit.ArkUI';
@Entry
@Component
struct Index {
modifier: NavModifier = new NavModifier();
build() {
Row() {
HMNavigation({
navigationId: 'Index',
homePageUrl: 'Main',
options: {
standardAnimator: HMDefaultGlobalAnimator.STANDARD_ANIMATOR,
dialogAnimator: HMDefaultGlobalAnimator.DIALOG_ANIMATOR,
modifier: this.modifier,
},
})
}
.width('100%')
.height('100%');
}
}
class NavModifier extends AttributeUpdater<NavigationAttribute> {
initializeModifier(instance: NavigationAttribute): void {
instance.hideNavBar(true);
}
}
使用@HMRouter
定义页面
typescript
import { HMRouter, HMRouterMgr } from '@hadss/hmrouter';
@HMRouter({
pageUrl: 'RemoveList',
})
@Component
export struct RemoveList {
build() {
Column() {
Text('RemoveList');
};
}
}
以上就HMRouter
的基本全套流程就完成了
我在项目中的调整
目前以PC项目为例
布局调整
在Index.ets
中调整HMNavigation
的位置
php
Row() {
Column() {
}
.width(200)
.height('100%')
.backgroundColor('#eee');
HMNavigation({
navigationId: 'Index',
homePageUrl: 'Main',
options: {
standardAnimator: HMDefaultGlobalAnimator.STANDARD_ANIMATOR,
dialogAnimator: HMDefaultGlobalAnimator.DIALOG_ANIMATOR,
modifier: this.modifier,
},
})
.layoutWeight(1);
}
.width('100%')
.height('100%');
这样在Column
中便利自己的nav
列表,添加点击跳转事件
scss
routers: RouterConfig[] = [{
router: 'Main',
name: '今日',
}, {
router: 'RemoveList',
name: '删除列表',
}];
ForEach(this.routers, (item: RouterConfig) => {
Text(item.name)
.lineHeight(30)
.onClick(() => {
const list = HMRouterMgr.getPathStack('Index');
console.log(list?.size().toString());
HMRouterMgr.push({
pageUrl: item.router,
});
});
});
完成后的简易效果
