• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# JS语法参考
2<!--Kit: ArkUI-->
3<!--Subsystem: ArkUI-->
4<!--Owner: @sunfei2021-->
5<!--Designer: @sunfei2021-->
6<!--Tester: @fredyuan912-->
7<!--Adviser: @HelloCrease-->
8
9JS文件用来定义HML页面的业务逻辑,支持ECMA规范的JavaScript语言。基于JavaScript语言的动态化能力,可以使应用更加富有表现力,具备更加灵活的设计能力。下面讲述JS文件的编译和运行的支持情况。
10
11
12## 语法
13
14支持ES6语法。
15
16- 模块声明
17  使用import方法引入功能模块:
18
19  ```js
20  import router from '@ohos.router';
21  ```
22
23- 代码引用
24  使用import方法导入js代码:
25
26  ```js
27  import utils from '../../common/utils.js';
28  ```
29
30
31## 对象
32
33- 应用对象
34  | 属性 | 类型   | 描述                                                         |
35  | ---- | ------ | ------------------------------------------------------------ |
36  | $def | Object | 使用`this.$app.$def`获取在app.js中暴露的对象。<br/>**说明:** <br/>应用对象不支持数据绑定,需主动触发UI更新。 |
37
38  示例代码
39
40  ```js
41  // app.js
42  export default {
43    onCreate() {
44      console.info('Application onCreate');
45    },
46    onDestroy() {
47      console.info('Application onDestroy');
48    },
49    globalData: {
50      appData: 'appData',
51      appVersion: '2.0',
52    },
53    globalMethod() {
54      console.info('This is a global method!');
55      this.globalData.appVersion = '3.0';
56    }
57  };
58  ```
59
60  ```js
61  // index.js页面逻辑代码
62  export default {
63    data: {
64      appData: 'localData',
65      appVersion:'1.0',
66    },
67    onInit() {
68      this.appData = this.$app.$def.globalData.appData;
69      this.appVersion = this.$app.$def.globalData.appVersion;
70    },
71    invokeGlobalMethod() {
72      this.$app.$def.globalMethod();
73    },
74    getAppVersion() {
75      this.appVersion = this.$app.$def.globalData.appVersion;
76    }
77  }
78  ```
79
80- 页面对象
81  | 属性     | 类型            | 描述                                                         |
82  | -------- | --------------- | ------------------------------------------------------------ |
83  | data     | Object/Function | 页面的数据模型,类型是对象或者函数,如果类型是函数,返回值必须是对象。属性名不能以\$或_开头,不要使用保留字for,&nbsp;if,&nbsp;show,&nbsp;tid。<br/>data字段不可与private/public字段同时使用。 |
84  | $refs    | Object          | 持有注册过ref&nbsp;属性的DOM元素或子组件实例的对象。示例见[获取DOM元素](#获取dom元素)。 |
85  | private  | Object          | 页面的数据模型,private下的数据属性只能由当前页面修改。      |
86  | public   | Object          | 页面的数据模型,public下的数据属性的行为与data保持一致。     |
87  | props    | Array/Object    | props用于组件之间的通信,可以通过&lt;tag&nbsp;xxxx='value'&gt;方式传递给组件;props名称必须用小写,不能以$或_开头,不要使用保留字for,&nbsp;if,&nbsp;show,&nbsp;tid。目前props的数据类型不支持Function。示例见[Props](../reference/apis-arkui/arkui-js/js-components-custom-props.md#props)。 |
88  | computed | Object          | 用于在读取或设置进行预先处理,计算属性的结果会被缓存。计算属性名不能以$或_开头,不要使用保留字。示例见[computed](../reference/apis-arkui/arkui-js/js-components-custom-props.md#computed)。 |
89
90## 方法
91
92- 数据方法
93  | 方法      | 参数                                     | 描述                                       |
94  | ------- | -------------------------------------- | ---------------------------------------- |
95  | $set    | key:&nbsp;string,&nbsp;value:&nbsp;any | 添加新的数据属性或者修改已有数据属性。<br/>用法:<br/>this.$set('key',value):添加数据属性。 |
96  | $delete | key:&nbsp;string                       | 删除数据属性。<br/>用法:<br/>this.$delete('key'):删除数据属性。 |
97
98  示例代码
99
100  ```js
101  // index.js
102  export default {
103    data: {
104      keyMap: {
105        OS: 'OS',
106        Version: '2.0',
107      },
108    },
109    getAppVersion() {
110      this.$set('keyMap.Version', '3.0');
111      console.info("keyMap.Version = " + this.keyMap.Version); // keyMap.Version = 3.0
112
113      this.$delete('keyMap');
114      console.info("keyMap.Version = " + this.keyMap); // log print: keyMap.Version = undefined
115    }
116  }
117  ```
118
119- 公共方法
120  | 方法         | 参数            | 描述                                                         |
121  | ------------ | --------------- | ------------------------------------------------------------ |
122  | $element     | id:&nbsp;string | 获得指定id的组件对象,如果无指定id,则返回根组件对象。示例见[获取DOM元素](#获取dom元素)。<br/>用法:<br/>&lt;div&nbsp;id='xxx'&gt;&lt;/div&gt;<br/>-&nbsp;`this.$element('xxx')`:获得id为xxx的组件对象。<br/>-&nbsp;`this.$element()`:获得根组件对象。 |
123  | $rootElement | 无              | 获取根组件对象。<br/>用法:<br/>this.\$rootElement().scrollTo({&nbsp;duration:&nbsp;500,&nbsp;position:&nbsp;300&nbsp;}),&nbsp;页面在500ms内滚动300px。 |
124  | $root        | 无              | 获得顶级ViewModel实例。[获取ViewModel](#获取viewmodel)示例。 |
125  | $parent      | 无              | 获得父级ViewModel实例。[获取ViewModel](#获取viewmodel)示例。 |
126  | $child       | id:&nbsp;string | 获得指定id的子级自定义组件的ViewModel实例。[获取ViewModel](#获取viewmodel)示例。<br/>用法:<br/>this.\$child('xxx')&nbsp;:获取id为xxx的子级自定义组件的ViewModel实例。 |
127
128- 事件方法
129  | 方法   | 参数                                                         | 描述                                                         |
130  | ------ | ------------------------------------------------------------ | ------------------------------------------------------------ |
131  | $watch | data:&nbsp;string,&nbsp;callback:&nbsp;string&nbsp;\|&nbsp;Function | 观察data中的属性变化,如果属性值改变,触发绑定的事件。示例见[\$watch感知数据改变](../reference/apis-arkui/arkui-js/js-components-custom-props.md#watch感知数据改变)。<br/>用法:<br/>this.$watch('key',&nbsp;callback):通过监听key属性值的变化,触发callback事件。 |
132
133- 页面方法
134  | 方法                    | 参数                               | 描述                              |
135  | --------------------- | -------------------------------- | ------------------------------- |
136  | scrollTo<sup>6+</sup> | scrollPageParam: ScrollPageParam | 将页面滚动到目标位置,可以通过ID选择器指定或者滚动距离指定。 |
137
138  **表1** ScrollPageParam<sup>6+</sup>
139
140  | 名称           | 类型                    | 默认值 | 描述                                                         |
141  | -------------- | ----------------------- | ------ | ------------------------------------------------------------ |
142  | position       | number                  | -      | 指定滚动位置。                                               |
143  | id             | string                  | -      | 指定需要滚动到的元素id。                                     |
144  | duration       | number                  | 300    | 指定滚动时长,单位为毫秒。                                   |
145  | timingFunction | string                  | ease   | 指定滚动动画曲线,可选值参考<br/>[动画样式animation-timing-function](../reference/apis-arkui/arkui-js/js-components-common-animation.md)。 |
146  | complete       | ()&nbsp;=&gt;&nbsp;void | -      | 指定滚动完成后需要执行的回调函数。                           |
147
148  示例:
149
150  ```js
151  this.$rootElement().scrollTo({ position: 0 });
152  this.$rootElement().scrollTo({ id: 'id', duration: 200, timingFunction: 'ease-in', complete: () => {
153      console.info('滚动已完成');
154  } });
155  ```
156
157
158## 获取DOM元素
159
1601. 通过$refs获取DOM元素
161   ```html
162   <!-- index.hml -->
163   <div class="container">
164     <image-animator class="image-player" ref="animator" images="{{images}}" duration="1s" onclick="handleClick"></image-animator>
165   </div>
166   ```
167
168   ```js
169   // index.js
170   export default {
171     data: {
172       images: [
173         { src: '/common/frame1.png' },
174         { src: '/common/frame2.png' },
175         { src: '/common/frame3.png' }
176       ]
177     },
178     handleClick() {
179       const animator = this.$refs.animator; // 获取ref属性为animator的DOM元素
180       const state = animator.getState();
181       if (state === 'Paused') {
182         animator.resume();
183       } else if (state === 'Stopped') {
184         animator.start();
185       } else {
186         animator.pause();
187       }
188     },
189   };
190   ```
191
1922. 通过$element获取DOM元素
193   ```html
194   <!-- index.hml -->
195   <div class="container" style="width:500px;height: 700px; margin: 100px;">
196     <image-animator class="image-player" id="animator" images="{{images}}" duration="1s" onclick="handleClick"></image-animator>
197   </div>
198   ```
199
200   ```js
201   // index.js
202   export default {
203     data: {
204       images: [
205         { src: '/common/frame1.png' },
206         { src: '/common/frame2.png' },
207         { src: '/common/frame3.png' }
208       ]
209     },
210     handleClick() {
211       const animator = this.$element('animator'); // 获取id属性为animator的DOM元素
212       const state = animator.getState();
213       if (state === 'Paused') {
214         animator.resume();
215       } else if (state === 'Stopped') {
216         animator.start();
217       } else {
218         animator.pause();
219       }
220     },
221   };
222   ```
223
224![zh-cn_image_0000001118642007](figures/zh-cn_image_0000001118642007.gif)
225
226## 获取ViewModel
227
228根节点所在页面:
229
230```html
231<!-- root.hml -->
232<element name='parentComp' src='../../common/component/parent/parent.hml'></element>
233<div class="container">
234  <div class="container">
235    <text>{{text}}</text>
236    <parentComp></parentComp>
237  </div>
238</div>
239```
240
241```js
242// root.js
243export default {
244  data: {
245    text: 'I am root!',
246  },
247}
248```
249
250![zh-cn_image_0000001118642008](figures/zh-cn_image_0000001118642008.png)
251
252自定义parent组件:
253
254```html
255<!-- parent.hml -->
256<element name='childComp' src='../child/child.hml'></element>
257<div class="item" onclick="textClicked">
258  <text class="text-style" onclick="parentClicked">parent component click</text>
259  <text class="text-style" if="{{showValue}}">hello parent component!</text>
260  <childComp id = "selfDefineChild"></childComp>
261</div>
262```
263
264```js
265// parent.js
266export default {
267  data: {
268    showValue: false,
269    text: 'I am parent component!',
270  },
271  parentClicked () {
272    this.showValue = !this.showValue;
273    console.info('parent component get parent text');
274    console.info(`${this.$parent().text}`);
275    console.info("parent component get child function");
276    console.info(`${this.$child('selfDefineChild').childClicked()}`);
277  },
278}
279```
280
281自定义child组件:
282
283```html
284<!-- child.hml -->
285<div class="item" onclick="textClicked">
286  <text class="text-style" onclick="childClicked">child component clicked</text>
287  <text class="text-style" if="{{isShow}}">hello child component</text>
288</div>
289```
290
291```js
292// child.js
293export default {
294  data: {
295    isShow: false,
296    text: 'I am child component!',
297  },
298  childClicked () {
299    this.isShow = !this.isShow;
300    console.info('child component get parent text');
301    console.info('${this.$parent().text}');
302    console.info('child component get root text');
303    console.info('${this.$root().text}');
304  },
305}
306```
307
308![zh-cn_image_0000001118642009](figures/zh-cn_image_0000001118642009.gif)