ArkTS装饰器 —— 39个

在这里插入图片描述

@Entry:入口组件

@Entry({
    routeName : 'myPage' })
@Component
struct MyComponent {
   
}
// 当useSharedStorage设置为true,并且storage也被赋值时,useSharedStorage的值优先级更高。
@Entry({
   
  routeName : 'myPage',  // 表示作为命名路由页面的名字。
  storage: storage,  // 页面级的UI状态存储。
  useSharedStorag: false,  // 是否使用LocalStorage.getShared()接口返回的LocalStorage实例对象
})

@Preview:组件预览

左侧图标为页面预览,右侧图标为组件预览
请添加图片描述

@Preview({
   
  title: 'ContentTable'
})
@Component
struct ContentTablePreview {
   
  build() {
   
    Flex() {
   
      ContentTable({
    foodItem: getDefaultFoodData() })
    }
  }
}

请添加图片描述

@Preview({
   
  title: 'Component1',  //预览组件的名称
  deviceType: 'phone',  //指定当前组件预览渲染的设备类型,默认为Phone
  width: 1080,  //预览设备的宽度,单位:px
  height: 2340,  //预览设备的长度,单位:px
  colorMode: 'light',  //显示的亮暗模式,当前支持取值为light
  dpi: 480,  //预览设备的屏幕DPI值
  locale: 'zh_CN',  //预览设备的语言,如zh_CN、en_US等
  orientation: 'portrait',  //预览设备的横竖屏状态,取值为portrait或landscape
  roundScreen: false  //设备的屏幕形状是否为圆形
})

ArkTS并发

并发是指在同一时间内,存在多个任务同时执行的情况。

异步并发

异步语法是一种编程语言的特性,允许程序在执行某些操作时不必等待其完成,而是可以继续执行其他操作。

异步代码会被挂起并在之后继续执行,同一时间只有一段代码执行,适用于单次I/O任务的场景开发,例如一次网络请求、一次文件读写等操作。无需另外启动线程执行。

Promise

import {
    BusinessError } from '@kit.BasicServicesKit';

const promise: Promise<number> = new Promise((resolve: Function, reject: Function) => {
   
  setTimeout(() => {
   
    const randomNumber: number = Math.random();
    if (randomNumber > 0.5) {
   
      // 成功
      resolve(randomNumber);
    } else {
   
      // 失败
      reject(new Error('Random number is too small'));
    }
  }, 1000);
})

promise.then((result: number) => {
   
 console.info(`Random number is ${
     result}`);
}).catch((error: BusinessError) => {
   
 console.error(error.message);
});

async/await

async function myAsyncFunction(): Promise<string> {
   
  const result: string = await new Promise((resolve: Function) => {
   
    setTimeout(() => {
   
      resolve('Hello, world!');
    }, 3000);
  });
  console.info(result); // 输出: Hello, world!
  return result;
}

@Entry
@Component
struct Index {
   
  @State message: string = 'Hello World';
  build() {
   
    Row() {
   
      Column() {
   
        Text(this.message)
          .onClick(async () => {
   
            let res = await myAsyncFunction();
            console.info("res is: " + res);
          })
      }
    }
  }
}
async function myAsyncFunction(): Promise<void> {
   
  try {
   
    const result: string = await new Promise((resolve: Function) => {
   
      resolve('Hello, world!');
    });
  } catch (e) {
   
    console.error(`Get exception: ${
     e}`);
  }
}

myAsyncFunction();

@Sendable:线程间通信对象

Class

@Sendable
class SendableTestClass {
   
  desc: string = "sendable: this is SendableTestClass ";
  num: number = 5;
  printName() {
   
    console.info("sendable: SendableTestClass desc is: " + this.desc);
  }
  get getNum(): number {
   
    return this.num;
  }
}

Function

@Sendable
type SendableFuncType = () => void;

@Sendable
class TopLevelSendableClass {
   
  num: number = 1;
  PrintNum() {
   
    console.info("Top level sendable class");
  }
}

@Sendable
function TopLevelSendableFunction() {
   
  console.info("Top level sendable function");
}

@Sendable
function SendableTestFunction() {
   
  const topClass = new TopLevelSendableClass(); // 顶层sendable class
  topClass.PrintNum();
  TopLevelSendableFunction(); // 顶层sendable function
  console.info("Sendable test function");
}

@Sendable
class SendableTestClass {
   
  constructor(func: SendableFuncType) {
   
    this.callback = func;
  }
  callback: SendableFuncType; // 顶层sendable function

  CallSendableFunc() {
   
    SendableTestFunction(); // 顶层sendable function
  }
}

let sendableClass = new SendableTestClass(SendableTestFunction);
sendableClass.callback();
sendableClass.CallSendableFunc();

@Concurrent:任务池

import {
    taskpool } from '@kit.ArkTS';

@Concurrent
function add(num1: number, num2: number): number {
   
  return num1 + num2;
}

async function ConcurrentFunc(): Promise<void> {
   
  try {
   
    let task: taskpool.Task = new taskpool.Task(add, 1, 2);
    console.info("taskpool res is: " + await taskpool.execute(task));
  } catch (e) {
   
    console.error("taskpool execute error is: " + e);
  }
}

@Entry
@Component
struct Index {
   
  @State message: string = 'Hello World'

  build() {
   
    Row() {
   
      Column() {
   
        Text(this.message)
          .fontSize(50)
          .fontWeight(FontWeight.Bold)
          .onClick(() => {
   
            ConcurrentFunc();
          })
      }
      .width('100%')
    }
    .height('100%')
  }
}

@CustomDialog:自定义弹出框

@CustomDialog
struct CustomDialogExample {
   
  controller: CustomDialogController = new CustomDialogController({
   
    builder: CustomDialogExample({
   }),
  })

  build() {
   
    Column() {
   
      Text('我是内容')
        .fontSize(20)
    }.height(60).justifyContent(FlexAlign.Center)
  }
}

@Entry
@Component
struct CustomDialogUser {
   
  dialogController: CustomDialogController = new CustomDialogController({
   
    builder: CustomDialogExample(),
  })

  build() {
   
    Column() {
   
      Button('click me')
        .onClick(() => {
   
          this.dialogController.open()
        })
    }.width('100%').margin({
    top: 5 })
  }
}

请添加图片描述

UI元素复用

@Builder:自定义构建函数

使用

@Builder
function builder1() {
   
  Text('Hello World')
}

@Entry
@Component
struct BuilderDemo {
   
  @Builder
  builder2() {
   
    Text('Hello World')
  }
  
  build() {
   
    Column() {
   
      // 全局自定义构建函数
      builder1()
      // 私有自定义构建函数
      this.builder2()
    }
  }
}

参数传递

只有传入一个参数,且参数需要直接传入对象字面量才会按引用传递该参数,其余传递方式均为按值传递。

@Builder function overBuilder(paramA1: string) {
   
  Row(
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值