文档

模板

更新时间:

axml 提供模板 template,您可以在模板中定义代码片段,然后在不同地方调用。

说明:建议使用 template 方式引入模版片段,因为 template 会指定其作用域,只使用 data 传入的数据,如果 templatedata 没有改变,该片段 UI 不会重新渲染。

定义模板

使用 name 属性申明模板名,然后在 <template/> 内定义代码片段。

  1. <!--
  2. index: int
  3. msg: string
  4. time: string
  5. -->
  6. <template name="msgItem">
  7. <view>
  8. <text> {{index}}: {{msg}} </text>
  9. <text> Time: {{time}} </text>
  10. </view>
  11. </template>

使用模板

使用 is 属性,声明需要的模板,然后将需要的 data 传入,比如:

  1. <template is="msgItem" data="{{...item}}"/>
  1. Page({
  2. data: {
  3. item: {
  4. index: 0,
  5. msg: 'this is a template',
  6. time: '2019-04-19',
  7. },
  8. },
  9. });

is 属性可以使用 Mustache 语法,来动态决定具体渲染哪个模板。

  1. <template name="odd">
  2. <view> odd </view>
  3. </template>
  4. <template name="even">
  5. <view> even </view>
  6. </template>
  7. <block a:for="{{[1, 2, 3, 4, 5]}}">
  8. <template is="{{item % 2 == 0 ? 'even' : 'odd'}}"/>
  9. </block>

模板作用域

模板有其作用域,只能使用 data 传入的数据。除了直接由 data 传入数据外,也可以通过 onXX 事件绑定页面逻辑进行函数处理。如下代码所示:

  1. <!-- templ.axml -->
  2. <template name="msgItem">
  3. <view>
  4. <view>
  5. <text> {{index}}: {{msg}} </text>
  6. <text> Time: {{time}} </text>
  7. </view>
  8. <button onTap="onClickButton">onTap</button>
  9. </view>
  10. </template>
  1. <!-- index.axml -->
  2. <import src="./templ.axml"/>
  3. <template is="msgItem" data="{{...item}}"/>
  1. Page({
  2. data: {
  3. item: {
  4. index: 0,
  5. msg: 'this is a template',
  6. time: '2019-04-22'
  7. }
  8. },
  9. onClickButton(e) {
  10. console.log('button clicked', e)
  11. },
  12. });
  • 本页导读 (0)
文档反馈