目录

Script

Defines page data and implements lifecycle APIs.

Syntax

  • eval cannot be used to execute JavaScript code.
  • new Function cannot be used to create a function.

The ES6 syntax is supported.

You can run the import command to import a function module. For details about how to call a module, please refer to the API reference.

import fetch from "@system.fetch"

You can also run the following command to import all function modules:

import system from "@system"

You can use system.network to call methods in APIs.

The import command is recommended in JavaScript code:

import utils from '../Common/utils.js'

Object

[h2]Page-Level Elements

Understand the differences between the protected, public, private, and data attributes. Data defined by the public and data attributes can be overwritten by external parameters with the same names as the attributes during startup. So, do not use the attributes to define sensitive or security variables, for example, binding the defined variables to the trustedUrl attribute of web components.

Attribute

Type

Description

data

(Deprecated)

object/function

Data model of a page, which can be converted into a JSON object. The attribute name cannot start with a dollar sign ($) or an underscore (_), or contain the reserved words such as for, if, show, and tid. If the type is a function, the return value must be an object, and data is set to the return value of the function during page initialization. This attribute is now reserved, and the public attribute is recommended. The data attribute cannot be used together with the private, protected, and public attributes.

private

object

Data model of a page. Variables under private can be modified only by code of the current page.

protected

object

Data model of a page. Values of the variables under protected can be changed by parameter passing during page redirection within the current app.

public

object

Data model of a page. Variables under public can be modified through URL passing, which is the same as the processing logic of the data attribute.

props

array

Public attribute list used to define elements (visible externally). This attribute can be passed to an element using <tag xxxx='value'>. The attribute name must be in lowercase and cannot start with a dollar sign ($) or an underscore (_) or contain the reserved words such as for, if, show, and tid. Currently, public attributes cannot be of the function type.

computed (1050+)

object

Calculation attribute. The attribute name cannot start with a dollar sign ($) or an underscore (_) or contain the reserved words such as for, if, show, and tid.

[h2]Custom Elements (1010+)

Attribute

Type

Description

data

object/function

Data model of a page, which can be converted into a JSON object. The attribute name cannot start with a dollar sign ($) or an underscore (_), or contain the reserved words such as for, if, show, and tid. If the type is a function, the return value must be an object, and data is set to the return value of the function during page initialization.

props

array/object

Public attribute list used to define elements (visible externally). This attribute can be passed to an element using <tag xxxx='value'>. The attribute name must be in lowercase and cannot start with a dollar sign ($) or an underscore (_) or contain the reserved words such as for, if, show, and tid. Currently, public attributes cannot be of the function type.

computed (1050+)

object

Calculation attribute. The attribute name cannot start with a dollar sign ($) or an underscore (_) or contain the reserved words such as for, if, show, and tid.

Sample code:

props: {
        // Check the type.
        a: Number,
        // Check the type and perform other verification.
        b: {
            type: Number,  // Check the type.
            default: 0,         // Default value
            required: true,  // Check mandatory items.
            validator: function (value) {  Check the validator function.
                // The value must match one of the following character strings:
                return ['success', 'warning', 'danger'].indexOf(value) !== -1
            }
        } 
}

[h2]Calculation Attributes (1050+)

Sample code:

export default {
    data: {
        firstName: 'Quick',
        lastName: 'App'
    },
    computed: {
        fullName: {
            get () {
                return `${this.firstName} ${this.lastName}`
            },
            set (value) {
                const names = value.split(' ')
                this.firstName = names[0]
                this.lastName = names[names.length - 1]
            }
        }
    },
    onReady () {
        console.log(this.fullName) // Quick App
        this.fullName = 'John Doe'
        console.log(this.firstName) // John
        console.log(this.lastName) // Doe
    }
}

[h2]Common Objects

Attribute

Type

Description

$app

object

App object.

$page

object

Page object.

$valid

boolean

Indicates whether a page object is valid.

$visible

boolean

Indicates whether a page is visible to users.

$attrs (1090+)

object

Passes values for high-priority elements.

$listeners (1090+)

object

Forwards all event listeners for cross-level elements.

$attrs:

The sample code is as follows:

//parent.ux
<template>
  <div class="item-content">
    <child attr1="attr1"></child>
  </div> 
</template>
//child.ux
<template>
  <div>
    <grandson $attrs></grandson>
    <input type="button" value="child" id="child-click" onclick="click" />
  </div>
</template>

<script>  
export default {    
     click() {
      this.childAttr1 = this.$attrs.attr1
    },
}  
</script> 
//grandson.ux
<template>
    <div class="box">
      <text class="title">Attr1:{{grandChildAttr1}}</text>
    <input type="button" value="grand-child" id="grand-child-click" onclick="click" />
    </div>
</template>

<script>  
export default {    
click() {
      this.grandChildAttr1 = this.$attrs.attr1
    },
} 
</script>

$listeners:

The sample code is as follows:

// parent.ux 
<template>   
   <div class="demo-page">     
      <child onevent1="handleEvent1"></child>   
   </div> 
</template>

<script> 
export default {   
   handleEvent1(evt) {     
      // do something!   
   } 
}
</script>
// child.ux 
<grandson $listeners></grandson> 
// grandson.ux 
<input type="button" value="grandson-event1" onclick="emitEvent1"/>  

<script>
export default {   
   emitEvent1() {  
      this.$emit('event1', {childName: 'grandson'})   
   } 
} 
</script>

[h2]App Objects

App objects can be accessed through $app.

Attribute

Type

Description

$def

object

this.$app.$def: Obtains objects exposed in the app.ux file.

$data

object

this.$app.$data: Obtains global data that is declared under config.data in the manifest.json file.

[h2]Page Objects

Page objects can be accessed through $page.

Attribute

Type

Description

action

string

Obtains actions of accessing the current page. This attribute is valid only when the current page is opened using the filter matching method. Otherwise, the attribute value is undefined. For details, please refer to Manifest File.

uri

string

Obtains the URI of the current page. This attribute is valid only when the current page is opened using the filter matching method. Otherwise, the attribute value is undefined. For details, please refer to Manifest File.

Methods

[h2]Data Methods

Attribute

Type

Parameter

Description

$set

function

key: string

value: any value

Adds a data attribute. This attribute must be used in the onInit function. If it is used in other functions, data binding in template cannot take effect.

Methods:

this.$set('key',value)

this.$vm('id').$set('key',value)

$delete

function

key: string

Deletes a data attribute. If this attribute is used in the onInit function, the corresponding data binding in template cannot take effect.

Methods:

this.$delete('key')

this.$vm('id').$delete('key')

[h2]Public Methods

Attribute

Type

Parameter

Description

$element

function

id: element ID, string

Obtains the dom object of the element with the specified ID. If the ID is not specified, the dom object of the root element is returned.

Methods:

<template><div id='xxx'></div></template>

  • this.$element('xxx'): obtains instance objects of the div element whose ID is xxx.
  • this.$element(): obtains instance objects of the root element.

$root

function

N/A

Obtains the top-level ViewModel.

$parent

function

N/A

Obtains the parent ViewModel.

$child

function

id: element ID, string

Obtains ViewModel of a custom element with the specified ID.

The this.$child('xxx') method obtains ViewModel from the element whose ID is xxx.

$rootElement

(Deprecated)

function

N/A

Obtains the dom object of the root element.

The this.$rootElement() method obtains the instance object of the root component, which is equivalent to this.$element().

$vm

(Deprecated)

function

id: element ID, string

Obtains ViewModel of a custom element with the specified ID.

The this.$vm('xxx') method obtains ViewModel from the div element whose ID is xxx.

$forceUpdate

function

N/A

Forcibly refreshes a page.

getApp

function

N/A

Obtains app information. This method is a global method and has the same as that of the $app object. An example is getApp().$data.appName;.

[h2]Event Methods

Attribute

Type

Parameter

Description

$on

function

  • type: event name, string
  • handler: event handler, function

Adds an event handler.

The method is in the format this.$on('xxxx', this.fn), where fn is a function defined in script.

$off

function

  • type: event name, string
  • handler: event handler, function

Deletes an event handler.

The method is in the format this.$off('xxxx', this.fn) . The this.$off('xxx') method is used to delete all handler of a specified event.

$dispatch

function

type: event name, string

Sends event notifications to the upper-level element.

The method is in the format this.$dispatch('xxx'). Event notifications (pop-up messages) are sent to the upper-level element until evt.stop() is called in the event handler.

$broadcast

function

type: event name, string

Sends event notifications to a subelement.

The method is in the format this.$broadcast('xxx'). Event notifications (pop-up messages) are sent to the subelement until evt.stop() is called in the event handler.

$emit

function

  • type: event name, string
  • data: event parameter, object

Triggers an event to call the corresponding handler.

The method is in the format this.$emit('xxx') or this.$emit('xxx', {a:1}). The passed event parameters can be accessed through evt.detail in the event callback function, for example, evt.detail.a.

$emitElement

function

  • type: event name, string
  • data: event parameter, object
  • id: element ID, string (The default value is -1, indicating the root element.)

Triggers an element event to call the corresponding handler.

The method is in the format this.$emitElement('xxx', null, 'id') or this.$emitElement('xxx', {a:1}). The passed event parameters can be accessed through evt.detail in the event callback function, for example, evt.detail.a.

$watch

function

  • data: attribute name, string (The value is a string in the format 'a.b.c', but not an array index.)
  • handler: event handler, string (The first parameter is the new attribute value, and the second parameter to the previous attribute value.)

Dynamically adds an attribute or binds an event. The attribute must be defined in the data attribute, and the handler function must be defined in script. The event is triggered only when the attribute value changes.

Method: this.$watch('a','handler')

[h2]App Methods

This app method can be accessed through $app.

Attribute

Type

Parameter

Description

exit

function

N/A

Exits the quick app and ends the app lifecycle. The onDestroy attributes of both the page and app are called.

[h2]Page Methods

Page methods can be accessed through $page.

Attribute

Type

Parameter

Description

setTitleBar

function

  • text: title bar text, string
  • textColor: text color, string
  • backgroundColor: background color, string
  • backgroundOpacity: transparency, number
  • menu: indicates whether to display the menu icon, Boolean

Sets the title bar of the current page.

Method: this.$page.setTitleBar({text:'Hello', textColor:'#FF0000', backgroundColor:'#FFFFFF',backgroundOpacity :0.5,menu: false})

name (1030+)

string

-

Obtains the name of the current page from the manifest file.

Method: this.$page.name

component (1030+)

string

-

Obtains the element name of the current page from the manifest file.

Method: this.$page.component

path (1030+)

string

-

Obtains the path of the current page from the manifest file.

Method: this.$page.path

finish

function

-

Exits the current page and ends the page lifecycle. The onDestroy attribute of the page will be called.

orientation(1040+)

string

-

Obtains the orientation of the current page from the manifest file.

Method: this.$page.orientation

  • portrait
  • landscape

statusBarHeight (1050+)

string

-

Obtains the height of the status bar.

Method: this.$page.statusBarHeight

windowHeight (1050+)

string

-

Obtains the window height of the current page.

Method: this.$page. windowHeight

windowWidth(1050+)

string

-

Obtains the window width of the current page.

Method: this.$page.windowWidth

setStatusBar (1050+)

function

  • immersive: indicates whether to enable the translucent status bar, Boolean
  • textStyle: text style, string
  • backgroundColor: background color of the status bar, string
  • backgroundOpacity: transparency of the status bar, number
  • visible (1079+): indicates whether to display the status bar, Boolean

Sets the status bar of the current page.

Method: this.$page.setStatusBar({immersive:true,textStyle:'dark', backgroundColor:'#FFFFFF', backgroundOpacity:0.5,visible:false})

exitFullscreen (1050+)

function

-

Exits the full-screen mode.

Method: this.$page.exitFullscreen ();

NOTE:

This method takes effect only when it is called in full screen mode by the video or stack element.

query (1060+)

object

-

Obtains the parameters carried in router after a page is opened, that is, a collection of parameters in uri and params.

Method: this.$page.query

scrollBy (1070+)

function

  • top: vertical scrolling offset, in pixels, number
  • behavior: scrolling behavior, string (The value can be smooth, instant, or auto. The default value is auto, which has the same effect as instant.)

Scrolls a page by the specified offset.

Method: this.$page.scrollBy({top:500, behavior:"smooth"});

NOTE:

This method takes effect only when the page is displayed, that is, after onShow or a later-phase method is called.

scrollTo (1070+)

function

  • top: vertical coordinate, number
  • behavior: scrolling behavior, string (The value can be smooth, instant, or auto. The default value is auto, which has the same effect as instant.)

Scrolls to a specified position on the page.

Method: this.$page.scrollTo({top:0, behavior:"smooth"});

setSecure (1073+)

function

secure: indicates whether to enable anti-screen capture, Boolean

Sets whether to enable anti-screen capture.

Method: this.$page.setSecure(true/false);

setNavigationBar(1079+)

function

visible: indicates whether the navigation bar is visible, Boolean

Sets the navigation bar of the current page.

Method: this.$page.setNavigationBar({visible:false});

CAUTION:

If visible of setNavigationBar is set to false, the status bar is not displayed no matter whether visible of setStatusBar is set to true or false.

setMenubarData(1090+)

function

  • shareTitle: shared title, string
  • shareDescription: shared description, string
  • shareIcon: shared image, string
  • shareCurrentPage: indicates whether the current page can be shared, Boolean, false by default
  • shareParams: key-value pairs in {"key":value} format transparently passed when the current page is shared, object
  • shareUrl(not supported currently): shared URL for quick app redirection on a device (for example, an iOS device) that does not support quick app, string
  • usePageParams: indicates whether to add the current page parameters to the shared parameters, Boolean
    • false: no
    • true: yes
    • default: depends on the value of shareCurrentPage (false: add; true: not add)
    CAUTION:

    If shareCurrentPage is set to true, do not add any sensitive information to the page parameter such as account number, passwords, and other security-relevant fields.

Sets MenubarData of the current page.

Method: this.$page.setMenubarData({shareTitle:·'Shared title', shareDescription:·'Shared description', shareIcon:'https://appimg.dbankcdn.com/application/icon144/b53a74c7982a47ea8c1c3f7408640989.png', shareCurrentPage:true, shareUrl:'https://developer.huawei.com', shareParams:"{\"key\":\"1\",\"id\":0}", usePageParams:true});

setMeta(1090+)

function

  • pic: path to the current cover image, string
  • description: description of the current page content, string

Enables whether the metadata can be crawled by crawlers in the form of common web pages.

Method: this.$page.setMeta({ pic:"the online address of the cover-image", description:"Hello" });

Lifecycle APIs

[h2]Page Lifecycle APIs

Attribute

Type

Parameter

Return Value

Description

Triggering Condition

onInit

function

N/A

N/A

Listens on page initialization.

Page initialization is complete. This API is called only once after page initialization.

onReady

function

N/A

N/A

Listens on page creation.

Page creation is complete and the page can be displayed. This API is called only once for one page.

onShow

function

N/A

N/A

Listens on page display.

A user accesses a page.

NOTE:

This API is not called when the root node of the page is a custom element. You are advised to use div as the root node.

onHide

function

N/A

N/A

Listens on page hiding.

A page is redirected to another.

onDestroy

function

N/A

N/A

Listens on page exit.

A page is redirected to another without entering the navigation stack.

onBackPress

function

N/A

boolean

Listens on actions triggered when the back button is tapped.

A user taps the back button.

  • If the return value is true, the page handles the return logic itself.
  • If the return value is false, the default return logic is used.
  • If no value is returned, the processing logic is the same as that of false.

onMenuPress

function

N/A

N/A

Listens on actions triggered when a menu button is tapped.

A user taps a menu button to the right of the action bar.

This configuration is invalid since the 1070 version.

onMenuButtonPress (1040+, only for Vision products, not formulated by the vendor alliance)

function

N/A

boolean

Listens on actions triggered when a menu key is pressed.

A user presses a menu key on the remote control.

  • If the return value is true, the page handles the return logic itself.
  • If the return value is false, the default return logic is used.
  • If no value is returned, the processing logic is the same as that of false.

onRefresh (1050+)

function

object

N/A

Listens to the reopening of a page.

  1. If launchMode is set to singleTask for a page in the manifest file, only one instance of this page can exist. If the page is opened multiple times, this function is called.
  2. If the push parameter carries the clearTask flag when a page is opened and an instance of the page already exists, this function is called.

The callback parameters are those carried when the page is re-opened.

For details, please refer to Page Launch Mode.

onConfigurationChanged (1060+)

function

An Object that contains the type parameter.

N/A

Listens on app configuration changes.

One of the following app settings is changed:

  • Language, country, or region
  • System theme mode
  • Screen orientation
  • Screen physical size

onReachTop (1080+)

function

N/A

N/A

Listens on actions triggered when a page is scrolled to top.

A page is scrolled to top.

onPageScroll (1080+)

function

N/A

function

Listens to page scrolling.

A page is scrolled.

onReachBottom (1080+)

function

N/A

N/A

Listens on actions triggered when a page is scrolled to bottom.

A page is scrolled to bottom.

type indicates the configuration change type. Currently, it has the following values.

Parameter Value

Description

locale

Change of the language or country/region.

themeMode(1083+)

Change of the theme mode.

orientation(1083+)

Change of the screen orientation when orientation in manifest is set to auto and auto-rotate is enabled.

NOTE:

You can call configuration.setScreenOrientation of the app configuration API to obtain the current screen orientation.

foldScreenMode (1083+)

Change of the screen physical size.

The sequence of calling the page lifecycle APIs is as follows:

[h2]App Lifecycle APIs

Attribute

Type

Parameter

Return Value

Description

Triggering Condition

onCreate

function

N/A

N/A

Listens on app creation.

A user creates an app.

onRequest (1070+)

function

N/A

N/A

Listens on app startup. This API is triggered only when minPlatformVersion is set to 1065 or a larger value.

An app is started.

onShow (1070+)

function

N/A

N/A

Listens on app display. This API is triggered only when minPlatformVersion is set to 1065 or a larger value.

An app is switched to the foreground.

onHide (1070+)

function

N/A

N/A

Listens on app hiding. This API is triggered only when minPlatformVersion is set to 1065 or a larger value.

An app is switched to the background.

onError (1030+)

function

Object, which contains the message and stack attributes. The message attribute indicates error message description, and stack indicates stack calling information about an error message.

N/A

Listens on app error information.

An app error occurs.

onPageNotFound (1060+)

function

N/A

Object, which contains only one attribute, uri. The attribute specifies the source link from which a user is redirected to an error page.

A user is redirected to an error page.

The engine redirects to an error page.

onDestroy

function

N/A

N/A

Listens on app destroy.

An app is destroyed.

onScreenChange(1079+)

function

N/A

string

Listens on the screen status change.

  • ACTION_SCREEN_OFF: The screen is off.
  • ACTION_SCREEN_ON: The screen is on.
  • ACTION_USER_PRESENT: The screen is unlocked.

The screen status is changed.

Message Channels

Messages can be communicated between pages through channels.

Usage: Create a message channel object.

const channel = new BroadcastChannel('channel1')

Attribute

Type

Parameter

Description

onmessage

function

Event: message object

Subscribes to messages.

channel.onmhttpsessage = function (event) {
console.log(event.data)
}

This preceding statement will obtain the message content through event.data.

postMessage

function

Object: message body

Releases messages.

channel.postMessage("hello world")

close

function

N/A

Disables a message channel.

channel.close()

Sample code:

The following sample code is used to create a message channel for the messageChannel page. When a message is received, the detail page is displayed. The message is sent through the message channel. When the messageChannel page receives the message, the toast notification box displays the message.

Code in the messageChannel.ux file is as follows:

<template>
    <div>
        <div>
            <text>{{componentName}}</text>
        </div>
        <div>
            <input type="button" onclick="creatChannel" value="Create a message channel."/>
            <input type="button" onclick="routeChannel" value="Redirect to the details page."/>
            <input type="button" onclick="cancelChannel" value="Disable the message channel."/>
        </div>
    </div>
</template>
<style>
    @import '../Common/css/common.css';
    .item-container {
        margin-bottom: 50px;
        margin-right: 60px;
        margin-left: 60px;
        flex-direction: column;
    }
</style>
<script>
    import prompt from '@system.prompt'
    import router from "@system.router"
    var channel;
    export default {
        data: {
            componentName: 'messageChannel',
        },
        onInit: function () {
            this.$page.setTitleBar({text: 'messageChannel'})
        },
        creatChannel: function () {
            channel = new BroadcastChannel('channel1');
            channel.onmessage = function (event) {
                console.log(event.data)
                prompt.showToast({message: 'Receive a message:' + event.data});
            };
        },
        routeChannel: function () {
            router.push({
                uri: '/Detail'
            });
        },
        cancelChannel: function () {
            channel.close();
        }
    }
</script>

Code in the detail.ux file is as follows:

<template>
  <div>
    <div>
      <text>{{componentName}}</text>
    </div>
    <div>
      <input type="button" onclick="postChannel" value="Send a message."/>
    </div>
  </div>
</template>
<style>
  @import '../../Common/css/common.css';
  .item-container {
    margin-bottom: 50px;
    margin-right: 60px;
    margin-left: 60px;
    flex-direction: column;
  }
</style>
<script>
  export default {
      data: {
          componentName: 'detail',
      },
      onInit: function () {
          this.$page.setTitleBar({text: 'detail'})
      },
      postChannel: function () {
          var channel = new BroadcastChannel('channel1');
          channel.postMessage("hello world");
      }
  }
</script>

The callback function channel.onmessage = function (event) { ..... }; is registered after the message channel is created. If you want to disable the message channel, you need to call the channel.close() method of the same message channel.

Links

[h2]FAQs

[h2]Cases