HarmonyOS 鸿蒙Next中谁能给几个自定义装饰器的示例

HarmonyOS 鸿蒙Next中谁能给几个自定义装饰器的示例 看了TS官网,到鸿蒙一堆报错,谁能来几个鸿蒙版的学习一下,各类型分别来一个

2 回复

鸿蒙Next中自定义装饰器的示例:

  1. 状态管理装饰器:
function @Observed(component: any) {
  component.isStateful = true;
}

@Observed
class MyComponent {
  // 组件逻辑
}
  1. 日志装饰器:
function @LogMethod(target: any, name: string, descriptor: PropertyDescriptor) {
  const original = descriptor.value;
  descriptor.value = function(...args: any[]) {
    console.log(`调用 ${name} 方法`);
    return original.apply(this, args);
  }
}

class MyService {
  @LogMethod
  fetchData() {
    // 获取数据
  }
}
  1. 权限检查装饰器:
function @RequirePermission(perm: string) {
  return function(target: any, name: string, descriptor: PropertyDescriptor) {
    const original = descriptor.value;
    descriptor.value = function(...args: any[]) {
      if(checkPermission(perm)) {
        return original.apply(this, args);
      }
      throw new Error("权限不足");
    }
  }
}

更多关于HarmonyOS 鸿蒙Next中谁能给几个自定义装饰器的示例的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


HarmonyOS Next自定义装饰器示例

在HarmonyOS Next中,你可以使用TypeScript装饰器来增强类的功能。以下是几种常见的装饰器示例:

1. 类装饰器

function logClass(target: Function) {
  console.log(`Class ${target.name} was defined`);
}

@logClass
class MyComponent {
  // 组件实现
}

2. 方法装饰器

function logMethod(target: any, propertyKey: string, descriptor: PropertyDescriptor) {
  const originalMethod = descriptor.value;
  
  descriptor.value = function(...args: any[]) {
    console.log(`Calling ${propertyKey} with args: ${JSON.stringify(args)}`);
    return originalMethod.apply(this, args);
  };
  
  return descriptor;
}

class MyService {
  @logMethod
  fetchData(url: string) {
    // 数据获取逻辑
  }
}

3. 属性装饰器

function defaultValue(value: any) {
  return function(target: any, propertyKey: string) {
    if (!target[propertyKey]) {
      target[propertyKey] = value;
    }
  };
}

class Settings {
  @defaultValue(100)
  timeout: number;
}

4. 参数装饰器

function validateParam(target: any, propertyKey: string, parameterIndex: number) {
  console.log(`Validating parameter at index ${parameterIndex} of ${propertyKey}`);
}

class Validator {
  checkInput(@validateParam input: string) {
    // 验证逻辑
  }
}

5. 访问器装饰器

function configurable(value: boolean) {
  return function(target: any, propertyKey: string, descriptor: PropertyDescriptor) {
    descriptor.configurable = value;
  };
}

class Config {
  private _mode: string = 'default';
  
  @configurable(false)
  get mode() {
    return this._mode;
  }
}

注意:在HarmonyOS Next中使用装饰器时,需要在tsconfig.json中启用实验性装饰器支持:

{
  "compilerOptions": {
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true
  }
}
回到顶部