HarmonyOS JS UI

1. Introduction

What is Hongmeng

Hongmeng OS (HarmonyOS, Hongmeng OS) is a distributed operating system for all scenarios. Its open source project is OpenHarmony.

history

  • In 2012, Huawei began planning its own operating system "Hongmeng"
  • On August 9, 2019, Huawei released Hongmeng 1.0
  • On September 10, 2020, Huawei released Hongmeng 2.0
  • On June 2, 2021, Hongmeng will be officially commercialized (Huawei officially released HarmonyOS 2 and a number of new products equipped with HarmonyOS 2)

Three characteristics of Hongmeng

  • super applet
    • H5 can only use browser functions
    • Mini programs can call functions of WeChat (scan code, take pictures, locate, check contacts)
    • Hongmeng can call system-level functions (threads), and can call functions of other devices
  • tailorable system
    • Can run on mobile phones, tablets, TVs, wearable devices, smart hardware and vehicle systems
    • Hongmeng can selectively run certain parts of the entire system according to the computing power of the system (chip)
  • Modified communication protocol
    • The standard language for IoT connectivity (phones, microwaves, refrigerators, cars, watches, headphones)
    • Similar to Mandarin, unified dialect

useful website

Harmonyos official website: https://www.harmonyos.com/
Harmony OS developers: https://developer.harmonyos.com/
Huawei developers: https://developer.huawei.com/
Online experience: https://playground .harmonyos.com/
Gitee: https://gitee.com/openharmony
JS API: https://developer.harmonyos.com/cn/docs/documentation/doc-references/js-apis-overview-0000001056361791

reserve knowledge

  • Familiar with front-end technology stack (HTML, CSS, JS)
  • Familiar with WeChat Mini Programs
  • Familiar with Vue
  • Android development experience is preferred

2. System architecture

The Hongmeng system architecture is divided into four layers: application layer, framework layer, system service layer, and kernel layer.

insert image description here
kernel layer

  • Kernel subsystem: HarmonyOS adopts multi-kernel design, which supports the selection of suitable OS kernels for different resource-constrained devices. Kernel Abstract Layer (KAL, Kernel Abstract Layer) provides basic kernel capabilities to the upper layer by shielding multi-core differences, including process/thread management, memory management, file system, network management, and peripheral management.
  • Driver subsystem: The hardware driver framework (HDF) is the foundation of the HarmonyOS hardware ecological openness, providing a unified peripheral access capability and a driver development and management framework.

System service layer
The system service layer is the core capability collection of HarmonyOS, which provides services to applications through the framework layer. This layer consists of the following parts:

  • System Basic Capabilities Subsystem Set: Provides basic capabilities for the operation, scheduling, and migration of distributed applications on HarmonyOS multi-device. It consists of distributed soft bus, distributed data management, distributed task scheduling, and Ark multilingual runtime , public basic library, multi-mode input, graphics, security, AI and other subsystems. Among them, the Ark runtime provides C/C++/JS multi-language runtime and basic system class libraries, and also provides Runtime.
  • Basic software service subsystem set: Provides common and general software services for HarmonyOS, consisting of subsystems such as event notification, telephone, multimedia, DFX (Design For X), MSDP & DV.
  • Enhanced software service subsystem set: Provide HarmonyOS with differentiated capability-enhanced software services for different devices, consisting of subsystems such as smart screen dedicated services, wearable dedicated services, and IoT dedicated services.
  • Hardware service subsystem set: Provides hardware services for HarmonyOS, consisting of subsystems such as location services, biometric identification, wearable dedicated hardware services, and IoT dedicated hardware services.

According to the deployment environment of different equipment forms, the interior of the basic software service subsystem set, enhanced software service subsystem set, and hardware service subsystem set can be tailored according to the granularity of the subsystem, and the interior of each subsystem can be tailored according to the granularity of the function.

Framework layer
The framework layer provides Java/C/C++/JS and other multi-language user program frameworks and Ability frameworks for HarmonyOS application development, and two UI frameworks (including the Java UI framework for the Java language and the JS UI for the JS language) framework), and a multilingual framework API open to the public for various software and hardware services. According to the degree of componentization and tailoring of the system, the APIs supported by HarmonyOS devices will also vary.

application layer

The application layer includes system applications and third-party non-system applications. HarmonyOS applications consist of one or more FA (Feature Ability) or PA (Particle Ability). Among them, FA has a UI interface, which provides the ability to interact with users; while PA has no UI interface, which provides the ability to run tasks in the background and a unified data access abstraction. The background data access required by FA for user interaction also needs to be supported by the corresponding PA. Applications developed based on FA/PA can realize specific business functions, support cross-device scheduling and distribution, and provide users with a consistent and efficient application experience.

JS UI framework architecture

JS UI framework includes application layer (Application), front-end framework layer (Framework), engine layer (Engine) and platform adaptation layer (Porting Layer).

View details: https://developer.harmonyos.com/en/docs/documentation/doc-guides/ui-js-overview-0000000000500376

insert image description here
application layer

Indicates the FA application developed by the developer using the JS UI framework.

The FA application here specifically refers to the JS FA application. Please refer to the development of FA applications using Java. Java UI framework

Front-end framework layer

It mainly completes the front-end page analysis, and provides capabilities such as MVVM (Model-View-ViewModel) development mode, page routing mechanism and custom components.

The engine layer
mainly provides animation analysis, DOM (Document Object Model) tree construction, layout calculation, rendering command construction and drawing, event management and other capabilities.

The adaptation layer
mainly completes the abstraction of the platform layer, provides an abstract interface, and can be connected to the system platform. For example: event docking, rendering pipeline docking and system life cycle docking, etc.

3. Build a development environment

DevEco Studio

See details: https://developer.harmonyos.com/cn/docs/documentation/doc-guides/installation_process-0000001071425528

Introduction
DevEco Studio is a one-stop distributed application development platform for all-scenario multi-device, supporting distributed multi-terminal development, distributed multi-terminal commissioning, multi-terminal simulation, and comprehensive quality and security assurance.
insert image description here
Environment Requirements
insert image description here
Download

Download address: https://developer.harmonyos.com/cn/develop/deveco-studio#download

insert image description here

Currently, Mac and Windows are two major operating systems. For your own operating system, just download the corresponding installation package (the following is a screenshot of the installation on Mac)

Install

Installation process
insert image description here

Specific steps

step Steps Operation guide illustrate
1 Software Installation Windows system software installation Install DevEco Studio
macOS system software installation
2 Configure the development environment (Optional) Set the Gradle proxy The network cannot directly access the Internet, and it needs to be set when it needs to be accessed through a proxy server. If you can access the Internet without a proxy, you can skip this step.
3 Configure the development environment (Optional) Set IDE Proxy The network cannot directly access the Internet, and it needs to be set when it needs to be accessed through a proxy server. If you can access the Internet without a proxy, you can skip this step.
4 Configure the development environment (Optional) Set up npm proxy The network cannot directly access the Internet, and it needs to be set when it needs to be accessed through a proxy server. If you can access the Internet without a proxy, you can skip this step.
5 Configure the development environment Download the HarmonyOS SDK -
6 Run HelloWorld create project Use the emulator to run the demo project to verify whether the environment has been configured.
7 Run HelloWorld run the application Use the emulator to run the demo project to verify whether the environment has been configured.

Execute the installation
insert image description here

run

insert image description here

SDK component installation

insert image description here
insert image description here

Agreement license, click Accept, then Next

Installing (downloading components), waiting...

After the installation is complete, click done. Then enter the welcome interface. There are four menus on the left

  • Create a Hongmeng project
  • open project
  • Get it in version control
  • Import Hongmeng example

Next, we can click on the first menu (Create HarmonyOS Project) to create a project.

Initialize the project

Click Create HarmonyOS Project on the welcome page

Here I choose List Tab Ability (JS)

insert image description here

insert image description here

4. Initialize the project

insert image description here
After the initialization is complete, you will see the following interface (the code of such a familiar directory looks very similar to a small program, does it matter~)

insert image description here
View the effect

Click on the Previewer on the right to view the effect (or View -> Tool Windows -> Previewer )

insert image description here

5. Install the simulator

Open Device Manager
insert image description here

register and log in

If you have not registered, please register for a Huawei developer account (registration address: https://developer.huawei.com/ );
if you have not logged in, please log in first. After logging in, you will see the following page

insert image description here
Real-name authentication
Click Go Authentication to see the following pop-up window. Then click here, and then jump to the Huawei developer website.
insert image description here

On the Huawei developer website, register as a developer.
insert image description here

Are there sensitive apps on the shelves?

  • If you choose Yes, the bank card authentication page will pop up (payment-related functions will be required later)
  • Select No, bank card authentication is recommended (not mandatory); however, we can choose ID card authentication.

insert image description here

Select Yes to perform bank card real-name authentication (3 minutes - the authentication speed is fast), and the effect after successful authentication is as follows:
insert image description here

Select No, and proceed with ID verification (1-2 business days - verification is slow).

insert image description here

Fill in the basic information and upload the ID card

insert image description here

Mentioned and pending review

Install the emulator

After the account authentication is passed, you can add the simulator in DevEco.
Tools -> Device Manager

insert image description here
After installation, see the following effect

insert image description here

Click Run to see how the project works on the simulator.

insert image description here

The difference between Simulator and Previewer:

  1. The previewer supports hot update, but the emulator does not support hot update
  2. Interface data cannot be returned directly in the previewer, but the simulator can return interface data

6. Sinicized menu

The Hongmeng operating system has just been launched. In order to face the international market faster, the editor uses English by default. The following introduces the Chineseization method.

Steps

  1. Click the menu File -> Settings,
  2. Then click Plugins -> Marketplate,
  3. Then search for Chinese,
  4. Then select Chinese (Simplified) Language Pack / Chinese Language Pack.
  5. Then click install to execute the installation

insert image description here

Restart the IDE after the installation is complete
insert image description here

Effect after reboot

As you can see, most of the menus are Chinese
insert image description here

Seven, JS framework

View details: https://developer.harmonyos.com/cn/documentation

insert image description here

Directory Structure

See details: https://developer.harmonyos.com/cn/docs/documentation/doc-references/js-framework-file-0000000000611396

instance directory

single instance directory

insert image description here

Multiple instance directory

insert image description here
File (directory) introduction

effect

  • app.js global entry file
  • pages store pages
  • common public resources
  • resources resource configuration file
  • i18n Multilingual Directory
  • share Multi-instance shared resource directory (5+)

Note:
The following folders are development reserved folders and cannot be renamed:
share
If the resources in the share and the resource files in the instance (default) have the same name and directory, the priority of the resources in the instance is higher than the priority of the resources in the share .
Other files can be created by themselves according to development needs.

access rules

Application resources can be accessed through absolute paths or relative paths. In this development framework, absolute paths start with "/", and relative paths start with "./" or ".../". The specific access rules are as follows:

  • To reference a code file, use a relative path, for example: .../common/utils.js.
  • To reference a resource file, it is recommended to use an absolute path. For example: /common/xxx.png.
  • Public code files and resource files are recommended to be placed under common and accessed through the above two rules.
  • The data type is created through the url() function in the CSS style file, such as: url(/common/xxx.png).

Page files
The files on the page are classified as follows:

  • .hml describes the layout structure of the page.
  • .css Describes page styles.
  • .js is used to handle the interaction between the page and the user.

resources

See details: https://developer.harmonyos.com/cn/docs/documentation/doc-guides/basic-resource-file-categories-0000001052066099

1 resources
2 |---base // 默认存在的目录
3 | |---element
4 | | |---string.json
5 | |---media
6 | | |---icon.png
7 |---en_GB-vertical-car-mdpi // 限定词目录示例,需要开发者自行创建
8 | |---element
9 | | |---string.json
10 | |---media
11 | | |---icon.png
12 |---rawfile // 默认存在的目录

resources directory classification

insert image description here
resource group directory
insert image description here

Use of resource files : https://developer.harmonyos.com/cn/docs/documentation/doc-guides/basic-resource-file-example-0000001051733014

8. Configuration file

config.json

Introduction

See details: https://developer.harmonyos.com/cn/docs/documentation/doc-guides/basic-config-file-overview-0000000000011951

It is recommended to understand the meaning of each configuration item in the form of a visual window in DevEco

There is a "config.json" configuration file in the root directory of each HAP of the application. The content of the file mainly covers the following three aspects:

  • The global configuration information of the application, including basic information such as the package name, manufacturer, and version number of the application.
  • The configuration information of the application on a specific device, including application backup and recovery, network security and other capabilities.
  • The configuration information of the HAP package includes the basic attributes that must be defined for each Ability (such as package name, class name, type, and the capabilities provided by the Ability), as well as the permissions required by the application to access the system or other protected parts of the application.

config.json is in JSON format. That is, the content is composed of attributes: values

  • Attributes, appearing in no particular order, and each attribute is only allowed to appear once at most.
  • Value, the value of each attribute is a basic data type of JSON (number, string, boolean, array, object or null type). If the attribute value needs to refer to a resource file, see Resource file.

Common configuration

See details: https://developer.harmonyos.com/cn/docs/documentation/doc-guides/basic-config-file-elements-0000000000034463

insert image description here

module

The configuration of the module is as follows

insert image description here
insert image description here
insert image description here
insert image description here

Application permission
reqPermissions

1 {
2 "module": {
3 "reqPermissions": [
4 {
5 "name": "ohos.permission.CAMERA",
6 "reason": "$string:permreason_camera",
7 "usedScene":
8 {
9 "ability": ["com.mycamera.Ability", "com.myca
mera.AbilityBackground"],
10 "when": "always"
11 }
12 },{

13 ...

14 }

15 ]

16 }
17 }

defPermissions

1 {
2 "module": {
3 "defPermissions": [
4 {
5 "name": "com.myability.permission.MYPERMISSION",
6 "grantMode": "system_grant",
7 "availableScope": ["signature"]
8 }, {
9 ...
10 }
11 ]
12 }
13 }

js

pages

1 "pages": [
2 "pages/index/index",
3 "pages/detail/detail"
4 ]

Note:
The first page in the pages list is the first page of the application, namely the entry entry.
The page file name cannot use the component name, such as: text.hml, button.hml, etc.

name
JS instance name
window
window is used to set the window configuration. For screen adaptation, there are two configuration methods:
specify designWidth (the logical width of the screen, the default is 720px on mobile phones and smart screens, and 454px by default on smart wearables), and all size-related styles (such as width, font-size) are set with The ratio between designWidth and actual screen width is scaled.

For example, when the designWidth is 720, if the width is set to 100px, on a screen with an actual width of 1440 physical pixels, the actual rendering pixels of the width are 200 physical pixels.

Set autoDesignWidth to true, then the designWidth field will be ignored, and the component and layout will be scaled according to the screen density. The logical width of the screen is automatically calculated by the device width and screen density, and may be different on different devices. Please use relative layout to adapt to multiple devices.

For example: on a device with 466*466 resolution and 320dpi, the screen density is 2 (based on 160dpi), and 1px is equal to 2 physical pixels rendered.

Configuration example

For details, refer to:
https://developer.harmonyos.com/en/docs/documentation/doc-guides/basic-config-file-example-0000000000034466

Nine, life cycle

application lifecycle

onCreate: Called when the application starts
onDestroy: Called when the application is destroyed

page life cycle

See details: https://developer.harmonyos.com/cn/docs/documentation/doc-references/js-framework-syntax-js-0000000000611432#ZH-CN_TOPIC_0000001058562835__s962b82fb67304ec9a50fb06ffa97756 0

insert image description here
insert image description here
The calling sequence of the life cycle interface of page A

  • Open page A: onInit() -> onReady() -> onShow() -> onActive()
  • Open page B on page A: onInactive() -> onHide()
  • Return to page A from page B: onShow() -> onActive()
  • Exit screen A: onBackPress() -> onInactive() -> onHide() -> onDestroy()
  • The page is hidden to run in the background: onInactive() -> onHide()
    The page is restored from the background to the foreground: onShow()

10. Routing and Navigation

Declare routes in config.json

1 {

2 // ...
3 "module": {
4 "js": [
5 {
6 // 声明⻚面路由
7 "pages": [
8 "pages/index/index",
9 "pages/details/details",
10 "pages/comp/comp"
11 ],
12 "name": "default",
13 "window": {
14 "designWidth": 720 ,
15 "autoDesignWidth": false
16 }
17 }
18 ]
19 }
20 }

Declare the corresponding three files in the pages directory
insert image description here
to declare navigation and
introduce router

1 import router from '@system.router';

Declare the navigation method

1 export default {
2 // ...
3
4 launch: function () {
5 router.push({
6 uri: 'pages/details/details',
7 });
8 }
9 }

In addition to the push method above, there are the following methods.
insert image description here

Eleven, JS syntax

For details, see: https://developer.harmonyos.com/cn/docs/documentation/doc-references/js-framework-syntax-js-0000000000611432
supports ES 6 syntax (but does not support the latest ES syntax).
Harmony JS is a reference to Vue 2 packaged

JS application

$def

In the page, through this. app . app.a pp.def , get the object exposed in app.js

data binding

data | public: the type is an object or a function
private: the data can only be modified by the current page

data modification

this. s e t ( ′ k e y ′ , v a l u e ) ; t h i s . set('key', value); this. set(key,value);this.delete(‘key’);

Get the DOM element

$refs

1 // index.hml
2 <text ref="target" >内容</div>
3
4 // index.js
5 const t = this.$refs.target; // 获取 ref 属性为 target 的 DOM 元素

$element

1 // index.hml
2 <text id="target" >内容</div>
3

4 // index.js
5 const t = this.$element("target"); // 获取 id 属性为 target 的 DOM
元素
6
7 // 获取根组件对象
8 const t = this.$element();

js architecture

12. HML syntax

HML (HarmonyOS Markup Language) is a set of HTML-like markup languages ​​that construct page content through components and events. The page has the capabilities of event binding, data binding, list rendering, conditional rendering and logic control.

See details:
https://developer.harmonyos.com/cn/docs/documentation/doc-references/js-framework-syntax-hml-0000000000611413

13. CSS Syntax

See details: https://developer.harmonyos.com/cn/docs/documentation/doc-references/js-framework-syntax-css-0000000000611425

basic grammar

Dimensions
only in pixels and percentages

style import
@import '…/…/common/style.css';

Precompiled
Hongmeng can directly parse sass and less (no need to install parsing plug-ins yourself)

screen adaptation

Based on design draft

Assuming the size of the design draft (assumption: 720 px), terminal size (assumption: 1440 px), the
scaling ratio is 1440 px /720 px = 2.0,
and the actual size is converted according to the scaling ratio 100 px X 2.0 = 200 px

Based on screen density

Screen density (dpi = dots per inch dots per inch)
ldpi: low density screen (~120dpi) (0.75 base density)
mdpi: medium density screen (~160dpi) (1.0 base density)
hdpi: high density screen (~240dpi) ( 1.5 base density)
xhdpi: extra high density screen (~320dpi) (2.0 base density)
xxhdpi: super extra high density screen (~480dpi) (3.0 base density)
xxxhdpi: extra extra high density screen (~640dpi) (4.0 base Density)
adaptation principle
Convert the actual size according to the base density (100 px X 2.0 = 200 px)

14. Multilingual support

See details: https://developer.harmonyos.com/en/docs/documentation/doc-references/js-framework-multiple-languages-0000000000625923

  • Language packs are stored in the i18n directory
    • language-region.json (zh-CN.json)
  • $t() Get the corresponding content
  • When switching the system language (in the emulator or real machine), you can see the effect

15. Components

Components are used to display page content, and their functional positioning is the same as that of HTML tags.

It should be emphasized that the components provided by Huawei do not run in the browser environment. Huawei components are more like components of applets.

However, in order to reduce learning costs, most of the component names provided by Huawei refer to the naming of HTML tags. For example: button, div,
input, etc. Although these component names are the same as HTML tag names, the attributes and usage are different. Please refer to official documents for details.

insert image description here
Basic components

Basic components provide basic content display functions and are some of the most commonly used components.

button
button

Provide button components, including capsule button, circle button, text button, arc button, download button.

See details: https://developer.harmonyos.com/cn/docs/documentation/doc-references/js-components-basic-button-0000000000621726

toggleStatus
button

See details: https://developer.harmonyos.com/cn/docs/documentation/doc-references/js-components-basic-toggle-0000001061155984

pieceA
block-like entry that can contain images and text. Often used to show recipients, for example: mail recipients or message recipients.

See details: https://developer.harmonyos.com/en/docs/documentation/doc-references/js-components-basic-piece-0000001060517794

Text
text
is used to display text information

See details: https://developer.harmonyos.com/cn/docs/documentation/doc-references/js-components-basic-text-0000000000611633


As <text>a subcomponent of span , it provides text modification capabilities

See details: https://developer.harmonyos.com/en/docs/documentation/doc-references/js-components-basic-span-0000000000611621

marquee
displays a line of text with a running light effect

See details: https://developer.harmonyos.com/cn/docs/documentation/doc-references/js-components-basic-marquee-0000000000611657

textarea
displays multiple lines of text

See details: https://developer.harmonyos.com/en/docs/documentation/doc-references/js-components-basic-textarea-0000000000611748

label
label component

See details: https://developer.harmonyos.com/en/docs/documentation/doc-references/js-components-basic-label-0000000000611688

The picture
image
is used to render and display pictures

See details: https://developer.harmonyos.com/en/docs/documentation/doc-references/js-components-basic-image-0000000000611597

image-animator
image frame animation

See details: https://developer.harmonyos.com/cn/docs/documentation/doc-references/js-components-basic-image-animator-0000001050066126

form

input
input box, including radio box, multi-select box, button and single-line text input box.

See details: https://developer.harmonyos.com/en/docs/documentation/doc-references/js-components-basic-input-0000000000611673

select
drop-down selection component

See details: https://developer.harmonyos.com/en/docs/documentation/doc-references/js-components-basic-select-0000000000611712

option
can be used <select>as <menu>a subcomponent of and to display content

For details, see: https://developer.harmonyos.com/cn/docs/documentation/doc-references/js-components-basic-option-0000000000611700

search
search component

See details: https://developer.harmonyos.com/en/docs/documentation/doc-references/js-components-basic-search-0000000000618599

switch switch
selector

See details: https://developer.harmonyos.com/cn/docs/documentation/doc-references/js-components-basic-switch-0000000000611736

rating
score bar

See details: https://developer.harmonyos.com/cn/docs/documentation/doc-references/js-components-basic-rating-0000000000611645

picker
, the type supports normal picker, date picker, time picker, time and date picker, multi-column text picker.

See details: https://developer.harmonyos.com/cn/docs/documentation/doc-references/js-components-basic-picker-0000000000621791

picker-view
slide selector embedded in the page

See details: https://developer.harmonyos.com/cn/docs/documentation/doc-references/js-components-basic-picker-view-0000001050119874

navigation

menu
provides a menu component, as a temporary popup window, used to display the operations that users can perform. Its child component is option

See details: https://developer.harmonyos.com/cn/docs/documentation/doc-references/js-components-basic-menu-0000000000618614

toolbar
toolbar

See details: https://developer.harmonyos.com/cn/docs/documentation/doc-references/js-components-basic-toolbar-0000001062209279

toolbar-item
toolbar subitem

See details: https://developer.harmonyos.com/cn/docs/documentation/doc-references/js-components-basic-toolbar-item-0000001061931453

other

slider
slider

See details: https://developer.harmonyos.com/en/docs/documentation/doc-references/js-components-basic-slider-0000000000611724

progress
progress bar

See details: https://developer.harmonyos.com/cn/docs/documentation/doc-references/js-components-basic-progress-0000000000611609

divider
divider, used to divide different content

See details: https://developer.harmonyos.com/en/docs/documentation/doc-references/js-components-basic-divider-0000000000618583

chart
icon component

See details: https://developer.harmonyos.com/cn/docs/documentation/doc-references/js-components-basic-chart-0000001050030933

qrcode
generates and displays QR codes

See details: https://developer.harmonyos.com/cn/docs/documentation/doc-references/js-components-basic-qrcode-0000001051089032

container component

div
is used as the root node of the page structure or to group content.

See details: https://developer.harmonyos.com/cn/docs/documentation/doc-references/js-components-container-div-0000000000611484

stack
stack container, sub-components are pushed onto the stack in order, and the latter sub-component covers the previous sub-component. (equivalent to z-index)

See details: https://developer.harmonyos.com/cn/docs/documentation/doc-references/js-components-container-stack-0000000000611521

badge
badge

See details: https://developer.harmonyos.com/cn/docs/documentation/doc-references/js-components-container-badge-0000001060267851

the list

A list contains a sequence of list items of equal width. It is suitable for presenting the same kind of data in a continuous, multi-line manner, such as pictures and texts.

See details: https://developer.harmonyos.com/cn/docs/documentation/doc-references/js-components-container-list-0000000000611496


<list>The subcomponent of list-item is used to display the specific item of the list

See details: https://developer.harmonyos.com/cn/docs/documentation/doc-references/js-components-container-list-item-0000000000611509


<list>The subcomponent of list-item-group is used to display the grouping, and the width is filled with the list component by default.

See details: https://developer.harmonyos.com/en/docs/documentation/doc-references/js-components-container-list-item-group-0000001050023049

grid

Provides grid layout effects, element layout through the grid system, mainly provides <grid-container><grid-row><grid-col> grid container components.
The grid system has three attributes: Margins, Gutters, and Columns.

  1. Margins: It is used to control the distance between the element and the edge of the screen. You can define different Margin values ​​according to the different sizes of the device as a unified specification in the breakpoint system.
  2. Gutters: It is used to control the distance relationship between elements and elements. According to different sizes of devices, different Gutters values ​​can be defined as a unified specification in the breakpoint system. In order to ensure a better visual effect, Gutters are usually not greater than the value of Margins.
  3. Columns: It is the main positioning tool used to assist layout. Different screen sizes match different numbers of Columns to assist layout positioning. The width of Columns automatically calculates the width of each Columns according to the width of the actual device and the number of Columns under the condition that Margins and Gutters conform to the specifications.

insert image description here

Grid breakpoint system
The grid system defines the relationship between the number of Columns corresponding to devices with different horizontal widths, forming a set of breakpoint rule definitions.

The grid system uses the horizontal resolution value as the breakpoint basis, and different devices display different numbers of grids according to their current horizontal width px value (autoDesignWidth is configured as true) within different breakpoint ranges.

  • xs: 0<horizontal resolution<320: 2 Columns grid;
  • sm: 320<=horizontal resolution<600: 4 Columns grid;
  • md: 600<=horizontal resolution<840: 8 Columns grid;
  • lg: 840 <= horizontal resolution: 12 Columns grid;

grid-container
grid layout container root node, including grid-row and grid-col grid layout.

See details: https://developer.harmonyos.com/cn/docs/documentation/doc-references/js-components-grid-container-0000001062133103

grid-row
grid-row is a sub-container component of the grid layout container grid-container. It uses flex horizontal layout to arrange each grid-col container. The default value of justify-content and align-items is flex-start, which supports wrapping display.

See details: https://developer.harmonyos.com/cn/docs/documentation/doc-references/js-components-grid-row-0000001062811276

grid-col
grid-col is a child container component of the grid layout container grid-row.

See details: https://developer.harmonyos.com/en/docs/documentation/doc-references/js-components-grid-col-0000001063130862

Tab

tabs
tab container

See details: https://developer.harmonyos.com/cn/docs/documentation/doc-references/js-components-container-tabs-0000000000611572

tab-bar
tab menu

See details: https://developer.harmonyos.com/cn/docs/documentation/doc-references/js-components-container-tab-bar-0000000000611548

tab-content

tab content

See details: https://developer.harmonyos.com/en/docs/documentation/doc-references/js-components-container-tab-content-0000000000611560

Pop-ups

dialog
custom popup

See details: https://developer.harmonyos.com/cn/docs/documentation/doc-references/js-components-container-dialog-0000001050068157

popup
bubble popup window

See details: https://developer.harmonyos.com/cn/docs/documentation/doc-references/js-components-container-popup-0000000000611584

panel
A slidable panel. Provides a lightweight content display window that can be easily switched between different sizes. Belongs to the popup component.

See details: https://developer.harmonyos.com/cn/docs/documentation/doc-references/js-components-container-panel-0000001062321291

step navigation

stepper
step navigator. When multiple steps are required to complete a task, the step navigator can be used to show the current progress.

See details: https://developer.harmonyos.com/en/docs/documentation/doc-references/js-components-container-stepper-0000001060518078

stepper-item

Step Navigation Subcomponent

See details: https://developer.harmonyos.com/cn/docs/documentation/doc-references/js-components-container-stepper-item-0000001060038131

Carousel

Carousel component
swiper

See details: https://developer.harmonyos.com/cn/docs/documentation/doc-references/js-components-container-swiper-0000000000611533

Pull down to refresh container

Pull down to refresh the container.
refresh

See details: https://developer.harmonyos.com/cn/docs/documentation/doc-references/js-components-container-refresh-0000000000618205

common components

media query

basic grammar

1 @media [media-type] [and|not|only] [(media-feature)] {
2 CSS-Code;
3 }

@media screen and (round-screen: true) { … } // condition is established when the device screen is round
@media (max-height: 800) { … } // range query, CSS level 3 writing
@media (height <= 800) { … } // Range query, CSS level 4 writing, equivalent to CSS level3
@media screen and (device-type: tv) or (resolution < 2) { … } // Contains both media type and Multi-condition complex statement query with multiple media features

import resources

1 @import url [media-type] [and|not|only] [(media-feature)];
2
3 # 例如
4 @import '../common/style.css' screen and (min-width: 600 ) and (max
-width: 1200 );

operator

and, or, not, and only are used to form complex media queries, and can also be combined through comma (,).
Range query was introduced in MediaQuery Level 4, enabling it to use max-, min-, and also supports <=, >=, <, > operators.

insert image description here

media features

insert image description here
insert image description here
insert image description here
insert image description here

custom components

Custom components are introduced to the host page through element.

1 <element name='comp' src='../../common/component/comp.hml'></eleme
nt>
2 <div>
3 <comp prop1='xxxx' @child1="bindParentVmMethod"></comp>
4 </div>
  • The name attribute refers to the custom component name (not required). The component name is not case-sensitive, and the default is lowercase. The src attribute refers to the hml file path of the custom component (required). If the name attribute is not set, the hml file name will be used as the component name by default.
  • Event binding: Bind subcomponent events in custom components using (on|@)child1) syntax, trigger events and pass them through this.$emit('child1', { params: 'pass parameters' }) in subcomponents value, the parent component executes the bindParentVmMethod method and receives the parameters passed by the child component.

Events named in camel case in child components need to use dashes to separate the naming forms when binding in the parent component, for example: @children-event means binding the childrenEvent event of the child component, such as @children-event="bindParentVmMethod ".

event delivery

Subcomponent
template file

1 <!-- comp.hml -->
2 <div class="item">
3 <text class="text-style" onclick="childClicked">点击这里查看隐藏文
本</text>
4 <text class="text-style" if="{
   
   {showObj}}">hello world</text>
5 </div>

js file

1 // comp.js
2 export default {
3 data: {
4 showObj: false,
5 },
6 childClicked () {
7 this.$emit('eventType1');
8 this.showObj = !this.showObj;
9 },
10 }

parent component

template file

1 <!-- xxx.hml -->
2 <element name='comp' src='../../common/component/comp.hml'></eleme
nt>
3 <div class="container">
4 <comp @event-type1="textClicked"></comp>
5 </div>

js file

1 // xxx.js
2 export default {
3 textClicked () {},
4 }

Parameter passing

Subcomponent
template file

1 <!-- comp.hml -->
2 <div class="item">

3 <text class="title-style">{
   
   {compProp}}</text>
4 </div>

js file

1 // comp.js
2 export default {
3 props: ['compProp'],
4 }

parent component

1 <!-- xxx.hml -->
2 <element name='comp' src='../../common/component/comp/comp.hml'></
element>
3 <div class="container">
4 <comp comp-prop="{
   
   {title}}"></comp>
5 </div>

Parent component comp-prop => child component compProp

set default

1 // comp.js
2 export default {
3 props: {
4 compProp: {
5 default: '123',
6 },
7 },
8 }

When the user does not set the value of comp-prop in the parent component, it will display 123 by default

data one-way

The data transfer between parent and child components is one-way. It can only be passed from the parent component to the child component. The child component cannot directly modify the value passed by the parent component. The value passed in by props can be received by data as the default value, and then Modify the value of data.

1 // comp.js
2 export default {
3 props: ['compProp'],
4 data() {
5 return {
6 count: this.compProp,
7 };
8 },
9 onClick() {
10 this.count = this.count + 1 ;
11 },
12 }

$watch

Monitor data changes

1 // comp.js
2 export default {
3 props: ['title'],
4 onInit() {
5 this.$watch('title', 'onPropertyChange');
6 },
7 onPropertyChange(newV, oldV) {
8 console.info('title 属性变化 ' + newV + ' ' + oldV);
9 },
10 }

computed

Computed property changes

In custom components, it is often necessary to pre-process when reading or setting a certain property. In this case, the computed field needs to be used. The getter and setter methods in computed are triggered when the property is read and written. The usage is as follows:

1 // comp.js
2 export default {
3 props: ['title'],
4 data() {
5 return {
6 objTitle: this.title,
7 time: 'Today',
8 };
9 },
10 computed: {
11 message() {
12 return this.time + ' ' + this.objTitle;
13 },
14 notice: {
15 get() {
16 return this.time;
17 },
18 set(newValue) {
19 this.time = newValue;
20 },
21 },
22 },
23 onClick() {
24 console.info('get click event ' + this.message);
25 this.notice = 'Tomorrow';
26 },
27 }

The first computed property message declared here has only a getter function by default, and the value of message will depend on the change of the value of objTitle. The getter function can only read and cannot change the value. When it needs to be assigned to a computed property, a setter function can be provided, such as the notice in the example.

event parameters

Subcomponents can also pass parameters upward through bound events. An example of adding parameters to custom events is as follows:
Subcomponents

template file

1 <!-- comp.hml -->
2 <div class="item">
3 <text class="text-style" onclick="childClicked">点击这里查看隐藏文
本</text>
4 <text class="text-style" if="{
   
   {showObj}}">hello world</text>
5 </div>

js file

1 // comp.js
2 export default {
3 childClicked () {
4 this.$emit('eventType1', {text: '收到子组件参数'});
5 this.showObj = !this.showObj;
6 },
7 }

parent component
template file

1 <!-- xxx.hml -->
2 <div class="container">
3 <text>父组件:{
   
   {text}}</text>
4 <comp @event-type1="textClicked"></comp>
5 </div>

js file

1 // xxx.js
2 export default {
3 data: {
4 text: '开始',
5 },
6 textClicked (e) {

7 this.text = e.detail.text;
8 },
9 }

slot

Anonymous Slot
Parent Component: <tag><text>Content </text></tag>
Child Component:<slot></slot>

Named Slot
Parent Component: <tag><text slot="slotname">Content </text></tag>
Child Component:<slot name="slotname"></slot>

16. Interface

Synchronous
After a synchronous method call, you must wait until the result is returned before continuing with subsequent operations.
Those without a callback function or with a Sync suffix are generally synchronous operations

1 var info = app.getInfo();
2 console.log(JSON.stringify(info));

asynchronous

When an asynchronous method is invoked, it does not block the work of the caller. After the business execution is completed, the callback function provided by the developer will be called.

With a callback function or without a Sync suffix, it is generally an asynchronous operation

1 device.getInfo({
2 success: function(data) {
3 console.log('成功,设备品牌:' + data.brand);
4 },
5 fail: function(data, code) {
6 console.log('失败. 错误码:'+ code + '; 错误信息: ' + data);
7 },
8 complete: function() {
9 console.log('get info complete');
10 },
11 });

Subscribe
After subscribing, the callback function will call back again when it is completed or when the event changes; it can be executed multiple times

For example: subscribe to geographic location, when the location changes, the callback function will be executed again.

1 geolocation.subscribe({
2 success: function(data) {
3 console.log('get location. latitude:' + data.latitude);
4 },
5 fail: function(data, code) {
6 console.log('fail to get location. code:' + code);
7 },
8 });

insert image description here

17. Basic functions

application context

See details: https://developer.harmonyos.com/en/docs/documentation/doc-references/js-apis-basic-features-context-0000000000611801

page routing

See details: https://developer.harmonyos.com/cn/docs/documentation/doc-references/js-apis-basic-features-routes-0000000000611824

Pop-ups

See details: https://developer.harmonyos.com/en/docs/documentation/doc-references/js-apis-basic-features-pop-up-0000000000611864

timer

See details: https://developer.harmonyos.com/cn/docs/documentation/doc-references/js-apis-basic-features-timer-0000001058085020

18. Network function

Upload Download

See details: https://developer.harmonyos.com/cn/docs/documentation/doc-references/js-apis-network-uploading-downloading-0000000000626076

data request

See details: https://developer.harmonyos.com/cn/docs/documentation/doc-references/js-apis-network-data-request-0000000000626077

19. File data

data storage

See details: https://developer.harmonyos.com/cn/docs/documentation/doc-references/js-apis-data-storage-0000000000626080

introduce

1 import storage from '@system.storage';

use

1 // 设置内容
2 storage.set({
3 key: 'storage_key',
4 value: 'storage value',
5 success: function() {
6 console.log('call storage.set success.');
7 },
8 fail: function(data, code) {
9 console.log('call storage.set fail, code: ' + code + ', data:
' + data);
10 },
11 });
12
13 // 获取内容
14 storage.get({
15 key: 'storage_key',
16 success: function(data) {
17 console.log('call storage.get success: ' + data);
18 },
19 fail: function(data, code) {
20 console.log('call storage.get fail, code: ' + code + ', data:
' + data);
21 },
22 complete: function() {
23 console.log('call complete');
24 },
25 });
26
27 // 删除内容
28 storage.delete({
29 key: 'Storage1',
30 success: function() {
31 console.log('call storage.delete success.');
32 },
33 fail: function(data, code) {
34 console.log('call storage.delete fail, code: ' + code + ', da
ta: ' + data);
35 },
36 });
37
38 // 清空内容
39 storage.clear({
40 success: function() {
41 console.log('call storage.clear success.');
42 },
43 fail: function(data, code) {
44 console.log('call storage.clear fail, code: ' + code + ', dat
a: ' + data);
45 },
46 });

file storage

See details: https://developer.harmonyos.com/cn/docs/documentation/doc-references/js-apis-file-storage-0000000000629445

storage directory
insert image description here

introduce

1 import file from '@system.file';

use

See details: https://developer.harmonyos.com/cn/docs/documentation/doc-references/js-apis-file-storage-0000000000629445

20. System functions

notification message

See details: https://developer.harmonyos.com/cn/docs/documentation/doc-references/js-apis-system-notification-0000000000626084

introduce

1 import notification from '@system.notification';

use

1 notification.show({
2 contentTitle: 'title info',
3 contentText: 'text',
4 clickAction: {
5 bundleName: 'com.huawei.testapp',
6 abilityName: 'notificationDemo',
7 uri: '/path/to/notification',
8 },
9 });

shock

See details: https://developer.harmonyos.com/en/docs/documentation/doc-references/js-apis-system-vibration-0000000000626085

introduce

1 import vibrator from '@system.vibrator';

use

1 vibrator.vibrate({
2 mode: 'short',
3 success() {
4 console.log('success to vibrate');
5 },
6 fail(data, code) {
7 console.log('handle fail, data = ${data}, code = ${code}');
8 },
9 });

sensor

See details: https://developer.harmonyos.com/cn/docs/documentation/doc-references/js-apis-system-sensor-0000000000626088

introduce

1 import sensor from '@system.sensor';

permissions

  • Pedometer: ohos.permission.ACTIVITY_MOTION
  • Heart rate: ohos.permission.READ_HEALTH_DATA
  • Acceleration: ohos.permission.ACCELEROMETER

use

1 // 观察加速度数据变化。再次调用时,会覆盖前一次调用效果,即仅最后一次调用生效。
2 sensor.subscribeAccelerometer({
3 interval: 'normal',
4 success: function(ret) {
5 console.log('get data x:' + ret.x);
6 console.log('get data y:' + ret.y);
7 console.log('get data z:' + ret.z);
8 },
9 fail: function(data, code) {
10 console.error("subscribe accelerometer fail, code: ' + code +
', data: ' + data);
11 },
12 });

13
14 // 订阅罗盘数据变化。再次调用时,会覆盖前一次调用效果,即仅最后一次调用生效。

15 sensor.subscribeCompass({
16 success: function(ret) {
17 console.log('get data direction:' + ret.direction);
18 },
19 fail: function(data, code) {
20 console.error("subscribe compass fail, code: ' + code + ', da
ta: ' + data);
21 },
22 });
23
24 // 订阅环境光线感应数据变化。再次调用时,会覆盖前一次调用效果,即仅最后一次调用
生效。
25 sensor.subscribeLight({
26 success: function(ret) {
27 console.log('get data intensity:' + ret.intensity);
28 },
29 fail: function(data, code) {
30 console.error('subscribe light fail, code: ' + code + ', dat
a: ' + data);
31 },
32 });
33
34 // 订阅计步传感器数据变化。再次调用时,会覆盖前一次调用效果,即仅最后一次调用生
效。
35 sensor.subscribeStepCounter({
36 success: function(ret) {
37 console.log('get step value:' + ret.steps);
38 },
39 fail: function(data, code) {
40 console.log('subscribe step count fail, code:' + code + ', da
ta:' + data);
41 },
42 });
43
44 // 订阅气压传感器数据变化。再次调用时,会覆盖前一次调用效果,即仅最后一次调用生
效。
45 sensor.subscribeBarometer({


46 success: function(ret) {
47 console.log('get data value:' + ret.pressure);
48 },
49 fail: function(data, code) {
50 console.log('subscribe barometer fail, code: ' + code + ', da
ta: ' + data);
51 },
52 });
53
54 // 订阅心率传感器数据变化。再次调用时,会覆盖前一次调用效果,即仅最后一次调用生
效。
55 sensor.subscribeHeartRate({
56 success: function(ret) {
57 console.log('get heartrate value:' + ret.heartRate);
58 },
59 fail: function(data, code) {
60 console.log('subscribe heart rate fail, code: ' + code + ', d
ata: ' + data);
61 },
62 });
63
64 // 订阅设备佩戴状态。再次调用时,会覆盖前一次调用效果,即仅最后一次调用生效。
65 sensor.subscribeOnBodyState({
66 success: function(ret) {
67 console.log('get on-body state value:' + ret.value);
68 },
69 fail: function(data, code) {
70 console.log('fail to get on body state, code:' + code + ', da
ta: ' + data);
71 },
72 });
73
74 // 获取设备佩戴状态。
75 sensor.getOnBodyState({
76 success: function(ret) {
77 console.log('on body state: ' + ret.value);
78 },
79 fail: function(data, code) {
80 console.log('handling fail, message: ' + data + ', code: ' +
code);
81 },

82 });

geographic location

For details, refer to: https://developer.harmonyos.com/cn/docs/documentation/doc-references/js-apis-system-location-0000000000626089
introduction

1 import geolocation from '@system.geolocation';

permissions

ohos.permission.LOCATION

use

1 // 获取位置信息
2 geolocation.getLocation({
3 success: function(data) {
4 console.log('经度:' + data.longitude);
5 console.log('纬度:' + data.latitude);
6 },
7 fail: function(data, code) {
8 console.log('fail to get location. code:' + code + ', data:'
+ data);
9 },
10 });

network status

For details, please refer to: https://developer.harmonyos.com/cn/docs/documentation/doc-references/js-apis-system-network-0000000000626092

permissions

  • ohos.permission.GET_WIFI_INFO
  • ohos.permission.GET_NETWORK_INFO
1 import network from '@system.network';

use

1 network.getType({
2 success: function(data) {
3 console.log('success get network type:' + data.type);
4 },
5 fail: function(data, code) {
6 console.log('fail to get network type code:' + code + ', dat
a:' + data);
7 },
8 });

Device Information

For details, please refer to: https://developer.harmonyos.com/cn/docs/documentation/doc-references/js-apis-system-device-info-0000000000626093

use

1 import device from '@system.device';

use

1 device.getInfo({
2 success: function(data) {
3 console.log('Device brand:' + data.brand);
4 },
5 fail: function(data, code) {
6 console.log('Error code:'+ code + '; Error information: ' + da
ta);
7 },
8 });

screen brightness

For details, please refer to: https://developer.harmonyos.com/en/docs/documentation/doc-references/js-apis-system-screen-brightness-0000001050025075

use

1 import brightness from '@system.brightness';

1 brightness.getValue({
2 success: function(data){
3 console.log('success get brightness value:' + data.value);
4 },
5 fail: function(data, code) {
6 console.log('get brightness fail, code: ' + code + ', data: '
+ data);
7 },
8 });y7

21. Official Demo

Some specific application examples provided by Hongmeng. There are codes, text introductions, and effect demonstrations

View details: https://developer.harmonyos.com/cn/develop/codelabs/

JS shopping application

For details, see: https://developer.huawei.com/consumer/cn/codelabsPortal/carddetails/JS-COMPONENTS

JS Pedometer Card

For details, see: https://developer.huawei.com/consumer/cn/codelabsPortal/carddetails/Step-Card

Distributed news sharing

For details, see:
https://developer.huawei.com/consumer/cn/codelabsPortal/carddetails/HarmonyOS-NewsClient

Distributed In-person Education

For details, see:
https://developer.huawei.com/consumer/cn/codelabsPortal/carddetails/HarmonyOS-EducationSystem

insert image description here

Guess you like

Origin blog.csdn.net/woyebuzhidao321/article/details/129411425