微信小程序(应用号)微信开发运营程序员

【0基础学习微信小程序】6.视图层(二)

2017-04-12  本文已影响0人  菜鸟窝

本文为菜鸟窝编辑吴佳林的连载。

【0基础学习微信小程序】5.视图层(上)中,我们介绍了视图层中的数据绑定,条件的渲染的功能,本篇文章将继续介绍其余几个功能。

列表渲染
在 WXML 如何要使用列表的功能,就需要使用列表渲染功能了。列表的渲染功能主要用到 wx:for,就是控制属性绑定一个数组,即可使用数组中各项的数据重复渲染该组件。

<view wx:for="{{array}}">
  {{index}}: {{item.message}}
</view>
Page({
  data: {
    array: [{
      message: 'foo',
    }, {
      message: 'bar'
    }]
  }
})

使用 wx:for-item 可以指定数组当前元素的变量名,
使用 wx:for-index 可以指定数组当前下标的变量名:

<view wx:for="{{array}}" wx:for-index="idx" wx:for-item="itemName">
  {{idx}}: {{itemName.message}}
</view>

模板
WXML提供模板,可以在模板中定义代码片段,然后在不同的地方调用。下面来看一下模板如何使用

1.定义模板

使用name属性,作为模板的名字。然后在 <template/> 内定义代码片段,如:

<template name="msgItem">
  <view>
    <text> {{index}}: {{msg}} </text>
    <text> Time: {{time}} </text>
  </view>
</template>

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

<template is="msgItem" data="{{...item}}"/>
    Page({
      data: {
        item: {
          index: 0,
          msg: 'this is a template',
          time: '2016-09-15'
        }
      }
    })

引用
WXML 提供两种文件引用方式import和include。

import
import可以在该文件中使用目标文件定义的template,如:
在 item.wxml 中定义了一个叫itemtemplate

```
<!-- item.wxml -->
<template name="item">
  <text>{{text}}</text>
</template>
```

在 index.wxml 中引用了 item.wxml,就可以使用item模板:

<import src="item.wxml"/>
<template is="item" data="{{text: 'forbar'}}"/>
    

include
include可以将目标文件除了<template/>的整个代码引入,相当于是拷贝到include位置,如:

<include src="header.wxml"/>
<view> body </view>
<include src="footer.wxml"/>
<view> header </view>
<view> footer </view>

更多内容,请关注菜鸟窝(微信公众号ID: cniao5),程序猿的在线学习平台。 转载请注明出处,本文出自菜鸟窝,原文链接http://www.cniao5.com/forum/thread/9b42a76019ea11e79e5100163e0230fa

上一篇 下一篇

猜你喜欢

热点阅读