【鸿蒙 Harmony】记录下今日份编写技巧:路由获取参数类型、lottie 动画组件

522 阅读2分钟

题记

今天也是写纯血鸿蒙的一天,记录下今日份编写的一些小技巧~

1、路由跳转获取参数

鸿蒙官方路由跳转,获取的参数是这样的:

 router.pushUrl({
  url: 'pages/Detail', // 目标url
  params: paramsInfo // 添加params属性,传递自定义参数
  })

class InfoTmp {
  age: number = 0
 }

class RouTmp {
  id: object = () => {
 }
  info: InfoTmp = new InfoTmp()
}

const params: RouTmp = router.getParams() as RouTmp

感觉使用起来很不得劲,又要声明类型,获取的时候还要还要转成对象。对于绝大部分业务来说,跳转携带的参数往往就一个 id、或者其他字段,这个时候每次这样感觉好麻烦

所以在自己封装的 AppRouter中 封装了个获取函数:

class AppRouter {

  
    /**
     * 获取路由参数
     * @param key: 访问路径如: user.info.name
     * @returns
     */
    getParams<T>(key?: string): T {
      const params = router.getParams();
      if (key == null) {
        return params as T
      } else {
        return key.split(".").reduce((value, current) => value[current] as object, params as object) as T
      }
    }
  
  
  /** ... 一些其他和路由相关的封装函数,比如拦截之类的  **/
}

使用:

跳转时,正常传递数据。

router.pushUrl({
  // 目标url
  url: 'pages/PageCategoryList',
  params: {
    id: item.id,
    test: {
      test: {
        name: "你好"
      }
    }
  }
}, router.RouterMode.Single);

获取参数时:

const id: number = appRouter.getParams("id")
const test: string = appRouter.getParams("test.test")
const testName: string = appRouter.getParams("test.test.name")
console.log("@路由参数:", id, JSON.stringify(test), testName)

//打印:@路由参数: 48 {"name":"你好"} 你好

2、Lottie 组件封装

鸿蒙中使用 lottie需要使用第三方库.

gitee.com/openharmony…

该依赖中使用步骤是:

  1. 声明 CanvasContext, 创建 Canvas
  2. 使用 lottie 加载 lottie 文件,绑定 Canvas

看起来步骤很简单,实际上很多时候我们项目中使用 Lottie,只是类似加载个动图来用用,很多复杂的操作用不着~,这样来看,这一套步骤下来就怪复杂了。

那我们直接将其封装成一个小组件,像使用 Image 一样使用就好了。代码如下(该功能实现比较简单,毕竟项目用不到太复杂的功能)

import lottie, { AnimationItem } from '@ohos/lottie'

@Component
export struct LottieImage {
  @Require @Prop private path: string
  private renderingSettings: RenderingContextSettings = new RenderingContextSettings(true) // 设置开启抗锯齿
  private renderingContext: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.renderingSettings) // 创建2D渲染上下文
  private animationItem?: AnimationItem

  aboutToAppear(): void {
    this.animationItem = lottie.loadAnimation({
      container: this.renderingContext, // 渲染上下文
      renderer: 'canvas', // 渲染方式
      loop: true, // 是否循环播放,默认true
      autoplay: true, // 是否自动播放,默认true
      contentMode: 'Contain', // 填充的模式
      frameRate: 30, //设置animator的刷帧率为30
      path: this.path, // json对象数据
    })
  }

  aboutToDisappear(): void {
    this.animationItem?.destroy()
  }

  build() {
    Canvas(this.renderingContext).width("100%").height("100%").onReady(() => {
      //抗锯齿的设置
      this.renderingContext.imageSmoothingEnabled = true;
      this.renderingContext.imageSmoothingQuality = 'medium'
    })
  }
}

封装后,使用如下:

LottieImage({ path: "common/lottie/ani_star_radiate.json" })
  .width(120)
  .height(120)

Bye~