鸿蒙分享(二):引入zrouter路由跳转+封装

码仓库:https://gitee.com/linguanzhong/share_harmonyos 鸿蒙api:12

鸿蒙第三方库地址:OpenHarmony三方库中心仓

zrouter地址:OpenHarmony三方库中心仓

1.引入zrouter

1.打开终端界面:输入 ohpm install @hzw/zrouter
2.在项目根目录的hvigor目录的hvigor-config.json5文件中配置安装 Sync Now或重新build让插件安装生效
复制代码
"router-register-plugin":"1.1.1"
3.导入router-register-plugin插件模块

3.1在common模块的hvigorfile.ts文件导入router-register-plugin插件模块,如下

复制代码
import { harTasks } from '@ohos/hvigor-ohos-plugin';
import { routerRegisterPlugin, PluginConfig } from 'router-register-plugin'

const config: PluginConfig = {
  scanDirs: ["src/main/ets/components"],
  logEnabled: true, // 查看日志
  viewNodeInfo: false, // 查看节点信息
  isAutoDeleteHistoryFiles: true // 删除无用编译产物
}

export default {
  system: harTasks,
  plugins: [routerRegisterPlugin(config)]
}

3.2 在entry模块的hvigorfile.ts文件导入router-register-plugin插件模块,如下

复制代码
import { hapTasks } from '@ohos/hvigor-ohos-plugin';
import { routerRegisterPlugin, PluginConfig } from 'router-register-plugin'

const config: PluginConfig = {
  scanDirs: ['src/main/ets/pages'],
  logEnabled: true, // 查看日志
  viewNodeInfo: false, // 查看节点信息
  isAutoDeleteHistoryFiles: false // 删除无用的编译产物

}

export default {
  system: hapTasks,
  plugins: [routerRegisterPlugin(config)]
}
4.初始化ZRouter

找到EntryAbility,onCreate方法添加如下代码

复制代码
    // 如果项目中存在hsp模块则传入true
    ZRouter.initialize((config) => {
      config.isLoggingEnabled = BuildProfile.DEBUG
      config.isHSPModuleDependent = true
      config.loadDynamicModule = ['@hzw/hara', 'harb', 'hspc']
      config.onDynamicLoadComplete = () => {
        console.log("已完成所有模块的加载")
      }
    })
5.使用

编辑器新建页面:NewPages.ets

手动添加页面则在entry--src--main--resoures--base--profile--main_pages.json 添加路径

代码如下:

复制代码
import { Route } from '@hzw/zrouter';

@Route({ name: "NewPages" })
@Entry
@Component
export struct NewPages {
  build() {
    NavDestination() {
      Text("NewPagesHelloWorld")
        .fontSize(50)
    }
    .height('100%')
    .width('100%')
  }
}

跳转:

2.封装

新建BaseRouter.ets 代码如下

复制代码
import { ZRouter } from '@hzw/zrouter';
import { OnPopCallback } from '@hzw/zrouter/src/main/ets/model/Model';

/**
 * 路由跳转
 */
export class BaseRouter {
  static readonly NewPages = "NewPages"

  /**
   * 页面跳转
   * BaseRouter.push(BaseRouter.WebViewPage, Object({title: "用户协议"}))
   */
  static push(name: string, params?: object, animated?: boolean, mode: LaunchMode = LaunchMode.STANDARD) {
    ZRouter.getInstance()
      .setLunchMode(mode)
      .setParam(params)
      .setAnimate(animated)
      .push(name)
  }

  //替换页面
  static replacePathByName(name: string, params?: object, animated?: boolean, mode: LaunchMode = LaunchMode.STANDARD) {
    ZRouter.replacePathByName(name, params, animated)
    ZRouter.getInstance().setLunchMode(mode).setParam(params).replace(name)
  }

  // 页面跳转带返回值
  public static pushForResult(name: string, param?: object, callback?: OnPopCallback) {
    ZRouter.pushForResult(name, param, callback)
  }

  //后退
  static back() {
    ZRouter.pop()
  }

  static clear() {
    ZRouter.clear()
  }

  //后退带返回值
  static backWithResult(params?: object) {
    ZRouter.popWithResult(params)
  }

  /**
   * 获取参数
   * @param key
   * @returns
   * 使用:BaseRouter.getParamName<string>("title") ?? ""
   */
  static getParamName<T>(key: string): T | undefined {
    let aa = ZRouter.getParam() as object
    if (aa) {
      return aa[key]
    }
    return undefined
  }
}

导出BaseRouter.ets

index.ets export { BaseRouter } from './src/main/ets/utils/BaseRouter'

1.修改index.ets

复制代码
import { ZRouter } from '@hzw/zrouter';
import { BaseRouter } from 'common';

@Entry
@Component
struct Index {
  build() {
    Navigation(ZRouter.getNavStack()) {
      Column() {
        Text("To NewPages")
          .fontSize(50).onClick(() => {
          BaseRouter.push(BaseRouter.NewPages, Object({
            title: "哈哈哈",
          }))
        })
      }
    }
    .height('100%')
    .width('100%')
  }
}

2.修改NewPages.ets

复制代码
import { Route } from '@hzw/zrouter';
import { BaseRouter } from 'common';

@Route({ name: BaseRouter.NewPages })
@Entry
@Component
export struct NewPages {
  @State title: string = '';

  aboutToAppear(): void {
  //获取传参
    this.title = BaseRouter.getParamName<string>("title") ?? ""
    console.log("title:"+this.title)
  }

  build() {
    NavDestination() {
      Text("NewPagesHelloWorld")
        .fontSize(50)
    }.title(this.title)
    .height('100%')
    .width('100%')
  }
}

3:点击text跳转

相关推荐
HarmonyOS小助手21 分钟前
【案例+1】HarmonyOS官方模板优秀案例 第7期:金融理财 · 记账应用
harmonyos·鸿蒙·鸿蒙生态
爱笑的眼睛112 小时前
HarmonyOS 应用开发深入浅出:基于 Stage 模型与声明式 UI 的现代化状态管理实践
华为·harmonyos
爱笑的眼睛113 小时前
HarmonyOS 应用开发深度解析:掌握 ArkTS 声明式 UI 与现代化状态管理
华为·harmonyos
爱笑的眼睛113 小时前
HarmonyOS 应用开发深度解析:基于 ArkTS 的跨组件状态管理最佳实践
华为·harmonyos
前端世界3 小时前
鸿蒙系统下的智能设备故障检测实战:从监控到自愈的全流程实现
华为·harmonyos
2501_919749033 小时前
flutter鸿蒙:使用flutter_local_notifications实现本地通知
flutter·华为·harmonyos
Georgewu12 小时前
【HarmonyOS 6】 The target can not be empty. check the build.profile,json5 file of
harmonyos
Georgewu13 小时前
【HarmonyOS 6】Install Failed: error: failed to install bundle.code:9568322
harmonyos
爱笑的眼睛1114 小时前
HarmonyOS 应用开发新范式:深入剖析 Stage 模型与 ArkTS 状态管理
华为·harmonyos
爱笑的眼睛1116 小时前
深入浅出 HarmonyOS ArkUI 3.0:基于声明式开发范式与高级状态管理构建高性能应用
华为·harmonyos