小程序循环列表和模板使用

列表循环就是相当于java中循环集合

列表使用json格式创建, 比如这个arrays

Page({
  data: {
    mo: 'Hello World!!',
    userid : '1234',
    userInfo: {},
    hasUserInfo: false,
    showInfo: '10',
    canIUse: wx.canIUse('button.open-type.getUserInfo'),

    arrays : [{
      meg : "hello"
    },{
      meg : "word"
    },{
      meg : "!!!"
    }]
  },

arrays的值是json格式的, json中 [] 表示数据组,  {} 表示对象

所以这里就有三个对象, meg是对象中的属性 (json格式可等同于java中的集合看待)

在如下wxml文件中操作:

<!--index.wxml-->
<view class="container">
  <view wx:for="{{arrays}}" wx:items="item" wx:key="index">
    <text id="msg_{{index}}">{{item.meg}}</text>
  </view>
</view>

wx:items是循环得到的值, 即一个对象{}, wx:key记录提当前是第几次循环, 从0开始

模板使用

定义模板数据,下面的item, itemxxx

Page({
  data: {
    mo: 'Hello World!!',
    userid : '1234',
    userInfo: {},
    hasUserInfo: false,
    showInfo: '10',
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    arrays : [{
      meg : "hello"
    },{
      meg : "word"
    },{
      meg : "!!!"
    }],
    item:{
      index : 0,
      msg : "this is a template",
      time : "2016-09-15"
    },
    itemxx: {
      index: 1000,
      msg: "this is a template 1000",
      time: new Date()
    }
  }

在前台使用模板数据, 如下不同数据使用同一模板, 因此更改模板就可以更改所有显示

<!--index.wxml-->
<view class="container">

  <template is="msgItem" data="{{...item}}"/>     <!--数据显示-->
  <template is="msgItem" data="{{...itemxx}}"/>   <!--取得不同数据, 但是也按照模板格式显示-->

  <template name="msgItem">                       <!--定义模板显示格式-->
    <view>
      <view>{{index}}</view>
      <view>{{msg}}</view>
      <view>{{time}}</view>
    </view>
  </template>

</view> 

猜你喜欢

转载自blog.csdn.net/lljxk2008/article/details/81099221
今日推荐