/**
* author: wn
* date: 2024/7/30 11:12
* description: 笔记
*/
/*
1 $$语法:内置组件双向同步
TextInput text
TextArea text
Checkbox select
DatePicker selected
TimePicker selected
Radio checked
Search value
Swiper index
2 aspectRatio 指定当前组件的宽高比,aspectRatio = width/height
3 linearGradient 渐变
direction: GradientDirection.Left ---> 箭头指向 颜色由 箭头根部 向 箭头 方向 填充
colors: [
['#FCA21C', 0], 颜色由 箭头根部 向 箭头 方向 填充 0 代表 从 位置 0 开始
['#FA6D1D', 1] 1 代表 在最后 结束 中间添加 0.3 0.5 分别代表 30% 50%的位置颜色
]
4 promptAction 弹窗
提示 弹窗 菜单弹窗
5 Navigation zRouter HMRouter
6 emitter 注册 发射 事件 传递数据
on, emit, once, emitter.off("eventId"), 取消eventID为"eventId"的所有事件回调处理函数
// 注册 接收数据
emitter.on({ eventId: 1 }, () => {
console.info('callback');
});
// 注册 发送数据 优先级
let eventData: emitter.EventData = {
data: {
"content": "c",
"id": 1,
}
};
let innerEvent: emitter.InnerEvent = {
eventId: 1,
priority: emitter.EventPriority.HIGH
};
emitter.emit(innerEvent, eventData);
7 HMRouter
版本要求 : HarmonyOS NEXT Developer Beta5及以上
1 下载安装
ohpm install @hadss/hmrouter
2 安装完成后 在项目根目录的(非 entry) configuration -- oh-package.json5 中 会自动注册好
{
"dependencies": {
"@hadss/hmrouter": "^1.0.0-rc.5"
}
}
3 修改项目根目录的(非 entry) configuration -- hvigor-config.json文件,加入路由编译插件
注意版本需要跟上一步 保持一致
--hmrouter-plugin 需要注意这里的写法--
"dependencies": {
"@hadss/hmrouter-plugin": "^1.0.0-rc.5" // 使用npm仓版本号
},
4 在项目根目录创建路由编译插件配置文件hmrouter_config.json(可选)
哪些目录中 用到 HM 需要加入到数组中
{
// 如果不配置则扫描src/main/ets目录,对代码进行全量扫描,如果配置则数组不能为空,建议配置指定目录可缩短编译耗时
"scanDir": ["src/main/ets/components","src/main/ets/interceptors"],
"saveGeneratedFile": false, // 默认为false,调试排除错误时可以改成true,不删除编译产物
}
5 在模块中引入路由编译插件, entry目录下 configuration--hvigorfile.ts
import { hapTasks } from '@ohos/hvigor-ohos-plugin';
import { hapPlugin } from '@hadss/hmrouter-plugin';
export default {
system: hapTasks,
plugins: [hapPlugin()] // 使用HMRouter标签的模块均需要配置,与模块类型保持一致
}
6 在工程目录(非 entry)下的build-profile.json5中,配置useNormalizedOHMUrl属性为true
{
"app": {
"products": [
{
"name": "default",
"signingConfig": "default",
"compatibleSdkVersion": "5.0.0(12)",
"runtimeOS": "HarmonyOS",
"buildOption": {
"strictMode": {
"useNormalizedOHMUrl": true
}
}
}
],
// ...其他配置
}
}
第七步可能是 模块化开发才会用到 后面验证 目前路径不对
7 在工程目录(非 entry)下的 oh-package.json5中配置对Har和Hsp的依赖,这里需要注意依赖的模块名称需要与模块的moduleName保持一致
{
"dependencies": {
"AppHar": "file:../AppHar", // AppHar库可以正确动态创建拦截器、生命周期和自定义转场动画对象
"@app/har": "file:../AppHar" // 错误使用方式,无法动态创建对象
}
}
快速开始
1 在UIAbility或者启动框架AppStartup中初始化路由框架
export default class EntryAbility extends UIAbility {
onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void {
HMRouterMgr.init({
context: this.context
})
}
}
2 主页中 -- Index
@Entry
@Component
export struct Index {
modifier: NavModifier = new NavModifier();
// 平板写法
build() {
// @Entry中需要再套一层容器组件,Column或者Stack
Column(){
// 使用HMNavigation容器
HMNavigation({
navigationId: 'mainNavigation', options: {
standardAnimator: HMDefaultGlobalAnimator.STANDARD_ANIMATOR,
dialogAnimator: HMDefaultGlobalAnimator.DIALOG_ANIMATOR,
modifier: modifier
}
}) {
Row() {
Button('点击跳转')
}
}
}
}
}
// 手机 APP 写法 -- homePageUrl 对应的是一个组件 而不是一个页面无需 @Entry
homePageUrl -- @HMRouter({ pageUrl: 'pageA'})
build() {
// @Entry中需要再套一层容器组件,Column或者Stack
Column(){
// 使用HMNavigation容器
HMNavigation({
navigationId: 'mainNavigation', homePageUrl:"pageA" options: {
standardAnimator: HMDefaultGlobalAnimator.STANDARD_ANIMATOR,
dialogAnimator: HMDefaultGlobalAnimator.DIALOG_ANIMATOR,
modifier: modifier
}
})
}
}
}
class NavModifier extends AttributeUpdater<NavigationAttribute> {
initializeModifier(instance: NavigationAttribute): void {
instance.mode(NavigationMode.Stack);
instance.navBarWidth('100%');
instance.hideTitleBar(true);
instance.hideToolBar(true);
}
}
PageA--
@HMRouter({ pageUrl: 'pageA'})
@Component
export struct PageA {
build() {
Text(`pageA`)
}
}
跳转
()=>{
HMRouterMgr.push({ navigationId: 'mainNavigation', pageUrl: 'pageB' })
HMRouterMgr.pop({ navigationId: 'mainNavigation', }) // 返回上一页
HMRouterMgr.pop({ navigationId: 'mainNavigation',pageUrl: 'pageA' }) // 返回A页
HMRouterMgr.replace({ navigationId: 'mainNavigation', pageUrl: 'pageA'}) // 替换为 A, A-B-C-replaceA -栈(A-B-A)
}
传参
HMRouterMgr.push({ navigationId: 'mainNavigation', pageUrl: 'pageB' , param : Object } ,{
第二个参数 是 其他页面返回该页面时触发的回调 ,该回调可以获取传递过来的参数
onResult(popInfo:HMPopInfo){
popInfo.srcPageInfo.name 其他页面的名字
popInfo.srcPageInfo.param 本页面向其他页面传递的数据
popInfo.result 其他页面传递的数据
}
})
目标页接收
aboutToAppear(){
HMRouterMgr.getCurrentParam() as Object
}
定义生命周期
被 HMRouter 管理的页面只走 aboutToAppear 与 aboutToDisAppear
因此要添加 他自己的生命周期管理
@HMLifecycle({ lifecycleName: 'pageLifecycle' })
export class pageLifecycle implements IHMLifecycle {
private time: number = 0;
onPrepare(ctx: HMLifecycleContext): void {
this.time = new Date().getTime();
}
onHidden(ctx: HMLifecycleContext): void {
const duration = new Date().getTime() - this.time;
console.log(`Page ${ctx.navContext?.pathInfo.name} stay ${duration}`);
}
}
@HMRouter({ pageUrl: 'pageOne', interceptors: ['LoginInterceptor'], lifecycle: 'pageLifecycle', animator: 'pageAnimator' })
定义拦截器
global: true 全局拦截器, false时 需要为对应的页面配置
@HMRouter({ pageUrl: 'pageA',interceptors: ['LoginInterceptor']})
@HMInterceptor({ interceptorName: 'LoginInterceptor', global: true })
export class LoginInterceptor implements IHMInterceptor {
handle(info: HMInterceptorInfo): HMInterceptorAction {
let connectionInfo: string = info.type === 'push' ? 'jump to' : 'back to';
console.log(`${info.srcName} ${connectionInfo} ${info.targetName}`)
return HMInterceptorAction.DO_NEXT; // 继续跳转
}
}
页面获取 其对应的 lifecycle 中的数据
@Observed
export class Model{
name:string
constructor( name:string )
}
lifecycle 中 数据定义为 对象 且用 @Observed 修饰 改变后是响应式的
onPrepare(){
model.name = '修改了'
}
页面中
@State model:Model = (HMRouterMgr.getCurrentLifecycleOwner().getLifecycle() as MyLifecycle).model
页面中 控制 lifecycle 的生命周期函数
aboutToAppear(){
HMRouterMgr.getCurrentLifecycleOwner()?.addObserver(HMLifecycleState.onBackPressed,()=>{
this,model.name = '修改本页面的对象 数据'
return true // 相当于 onBackPressed直接返回 其lifecycle中的代码不再执行
})
}
HMRouter 生命周期顺序 建议 耗时操作放在 Lifecycle 的 onPrepare 中
点击跳转 -- onPrepare -- 转场动画 -- aboutToAppear -- 处理页面数据 -- UI渲染
*/
Harmony OS Next 项目笔记 HMRouter
于 2024-11-25 10:07:36 首次发布