JS语法参考

JS文件用来定义HML页面的业务逻辑,支持ECMA规范的JavaScript语言。基于JavaScript语言的动态化能力,可以使应用更加富有表现力,具备更加灵活的设计。下面讲述JS文件的编译和运行的支持情况。

语法

支持ES6语法。

  • 模块声明

    使用import方法引入功能模块:

    import router from '@system.router';
    
  • 代码引用

    使用import方法导入js代码:

    import utils from '../../common/utils.js';
    

对象

  • 应用对象

    属性

    类型

    描述

    $def

    Object

    使用this.$app.$def获取在app.js中暴露的对象。

    说明:

    应用对象不支持数据绑定,需主动触发UI更新。

    示例代码

    // app.js
    export default {
      onCreate() {
        console.info('AceApplication onCreate');
      },
      onDestroy() {
        console.info('AceApplication onDestroy');
      },
      globalData: {
        appData: 'appData',
        appVersion: '2.0',
      },
      globalMethod () {
        console.info('This is a global method!');
        this.globalData.appVersion = '3.0';
      }
    };
    
    // index.js页面逻辑代码
    export default {
      data: {
        appData: 'localData',
        appVersion:'1.0',
      },
      onInit() {
        this.appData = this.$app.$def.globalData.appData;
        this.appVersion = this.$app.$def.globalData.appVersion;
      },
      invokeGlobalMethod() {
        this.$app.$def.globalMethod();
      },
      getAppVersion() {
        this.appVersion = this.$app.$def.globalData.appVersion;
      }
    }
    
  • 页面对象

    属性

    类型

    描述

    data

    Object/Function

    页面的数据模型,类型是对象或者函数,如果类型是函数,返回值必须是对象。属性名不能以$或_开头,不要使用保留字for, if, show, tid。

    data与private和public不能重合使用。

    $refs

    Object

    持有注册过ref 属性的DOM元素或子组件实例的对象。示例见获取DOM元素

    private

    Object

    页面的数据模型,private下的数据属性只能由当前页面修改。

    public

    Object

    页面的数据模型,public下的数据属性的行为与data保持一致。

    props

    Array/Object

    props用于组件之间的通信,可以通过<tag xxxx='value'>方式传递给组件;props名称必须用小写,不能以$或_开头,不要使用保留字for, if, show, tid。目前props的数据类型不支持Function。示例见自定义组件

    computed

    Object

    用于在读取或设置进行预先处理,计算属性的结果会被缓存。计算属性名不能以$或_开头,不要使用保留字。示例见自定义组件

方法

  • 数据方法

    属性

    类型

    参数

    描述

    $set

    Function

    key: string

    value: any

    添加新的数据属性或者修改已有数据属性。

    用法:

    this.$set('key',value):添加数据属性。

    $delete

    Function

    key: string

    删除数据属性。

    用法:

    this.$delete('key'):删除数据属性。

    示例代码

    export default {
      data: {
        keyMap: {
          OS: 'OpenHarmony',
          Version: '2.0',
        },
      },
      getAppVersion() {
        this.$set('keyMap.Version', '3.0');
        console.info("keyMap.Version = " + this.keyMap.Version); // keyMap.Version = 3.0
    
        this.$delete('keyMap');
        console.info("keyMap.Version = " + this.keyMap); // log print: keyMap.Version = undefined
      }
    }
    
  • 公共方法

    属性

    类型

    参数

    描述

    $element

    Function

    id: string 组件id

    获得指定id的组件对象,如果无指定id,则返回根组件对象。示例见获取DOM元素

    用法:

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

    • this.$element('xxx'):获得id为xxx的组件对象。
    • this.$element():获得根组件对象。

    $root

    Function

    获得顶级ViewModel实例。获取ViewModel示例。

    $parent

    Function

    获得父级ViewModel实例。获取ViewModel示例。

    $child

    Function

    id: string 组件id

    获得指定id的子级自定义组件的ViewModel实例。获取ViewModel示例。

    用法:

    this.$child('xxx') :获取id为xxx的子级自定义组件的ViewModel实例。

  • 事件方法

    属性

    类型

    参数

    描述

    $watch

    Function

    data: string

    callback: 函数名,回调函数里有两个参数,第一个参数为属性新值,第二个参数为属性旧值

    观察data中的属性变化,如果属性值改变,触发绑定的事件。示例见自定义组件

    用法:

    this.$watch('key', callback)

获取DOM元素

  1. 通过$refs获取DOM元素

    <!-- index.hml -->
    <div class="container">
      <image-animator class="image-player" ref="animator" images="{{images}}" duration="1s" onclick="handleClick"></image-animator>
    </div>
    
    // index.js
    export default {
      data: {
        images: [
          { src: '/common/frame1.png' },
          { src: '/common/frame2.png' },
          { src: '/common/frame3.png' },
        ],
      },
      handleClick() {
        const animator = this.$refs.animator; // 获取ref属性为animator的DOM元素
        const state = animator.getState();
        if (state === 'paused') {
          animator.resume();
        } else if (state === 'stopped') {
          animator.start();
        } else {
          animator.pause();
        }
      },
    };
    
  2. 通过$element 方法获取DOM元素

    <!-- index.hml -->
    <div class="container">
      <image-animator class="image-player" id="animator" images="{{images}}" duration="1s" onclick="handleClick"></image-animator>
    </div>
    
    // index.js
    export default {
      data: {
        images: [
          { src: '/common/frame1.png' },
          { src: '/common/frame2.png' },
          { src: '/common/frame3.png' },
        ],
      },
      handleClick() {
        const animator = this.$element('animator'); // 获取id属性为animator的DOM元素
        const state = animator.getState();
        if (state === 'paused') {
          animator.resume();
        } else if (state === 'stopped') {
          animator.start();
        } else {
          animator.pause();
        }
      },
    };
    

获取ViewModel

根节点所在页面:

<!-- root.hml -->
<element name='parentComp' src='../../common/component/parent/parent.hml'></element>
<div class="container">
  <div class="container">
    <text>{{text}}</text>
    <parentComp></parentComp>
  </div>
</div>
// root.js
export default {
  data: {
    text: 'I am root!',
  },
}

自定义parent组件:

<!-- parent.hml -->
<element name='childComp' src='../child/child.hml'></element>
<div class="item" onclick="textClicked">
  <text class="text-style" onclick="parentClicked">parent component click</text>
  <text class="text-style" if="{{show}}">hello parent component!</text>
  <childComp id = "selfDefineChild"></childComp>
</div>
// parent.js
export default {
  data: {
    show: false,
    text: 'I am parent component!',
  },
  parentClicked () {
    this.show = !this.show;
    console.info('parent component get parent text');
    console.info(`${this.$parent().text}`);
    console.info("parent component get child function");
    console.info(`${this.$child('selfDefineChild').childClicked()}`);
  },
}

自定义child组件:

<!-- child.hml -->
<div class="item" onclick="textClicked">
  <text class="text-style" onclick="childClicked">child component clicked</text>
  <text class="text-style" if="{{show}}">hello child component</text>
</div>
// child.js
export default {
  data: {
    show: false,
    text: 'I am child component!',
  },
  childClicked () {
    this.show = !this.show;
    console.info('child component get parent text');
    console.info('${this.$parent().text}');
    console.info('child component get root text');
    console.info('${this.$root().text}');
  },
}

生命周期接口

  • 页面生命周期

    属性

    类型

    参数

    返回值

    描述

    触发时机

    onInit

    Function

    页面初始化

    页面数据初始化完成时触发,只触发一次。

    onReady

    Function

    页面创建完成

    页面创建完成时触发,只触发一次。

    onShow

    Function

    页面显示

    页面显示时触发。

    onHide

    Function

    页面消失

    页面消失时触发。

    onDestroy

    Function

    页面销毁

    页面销毁时触发。

    onBackPress

    Function

    Boolean

    返回按钮动作

    当用户点击返回按钮时触发。

    • 返回true表示页面自己处理返回逻辑。
    • 返回false表示使用默认的返回逻辑。
    • 不返回值会作为false处理。

    onActive()5+

    Function

    页面激活

    页面激活时触发。

    onInactive()5+

    Function

    页面暂停

    页面暂停时触发。

    onNewRequest()5+

    Function

    FA重新请求

    该回调当FA已经启动时收到新的请求后触发。

    页面A的生命周期接口的调用顺序

    • 打开页面A:onInit() -> onReady() -> onShow() -> onActive()
    • 在页面A打开页面B:onInactive() -> onHide()
    • 从页面B返回页面A:onShow() -> onActive()
    • 退出页面A:onBackPress() -> onInactive() -> onHide() -> onDestroy()
    • 页面隐藏到后台运行:onInactive() -> onHide()
    • 页面从后台运行恢复到前台:onShow()
  • 应用生命周期

    属性

    类型

    参数

    返回值

    描述

    触发时机

    onCreate

    Function

    应用创建

    当应用创建时调用。

    onDestroy

    Function

    应用退出

    当应用退出时触发。