# 列表渲染

# qa:for

使用 qa:for 控制属性绑定数组,可以批量渲染一个组件。渲染时,数组当前项的默认下标变量名为 index,数组当前项的默认变量名为 item,可以在模板中直接使用。

<view qa:for="{{array}}">
  {{index}}: {{item.message}}
</view>
1
2
3
Page({
  data: {
    array: [
      {
        message: 'msg1'
      },
      {
        message: 'msg2'
      }
    ]
  }
})
1
2
3
4
5
6
7
8
9
10
11
12

使用 qa:for-item 可以修改当前项的默认变量名,

使用 qa:for-index 可以修改当前项的默认下标变量名:

<view qa:for="{{array}}" qa:for-index="idx" qa:for-item="itemName">
  {{idx}}: {{itemName.message}}
</view>
1
2
3

qa:for 也可以嵌套,以九九乘法表为例:

<view qa:for="{{[1, 2, 3, 4, 5, 6, 7, 8, 9]}}" qa:for-item="i">
  <view qa:for="{{[1, 2, 3, 4, 5, 6, 7, 8, 9]}}" qa:for-item="j">
    <view qa:if="{{i <= j}}">
      {{i}} * {{j}} = {{i * j}}
    </view>
  </view>
</view>
1
2
3
4
5
6
7

# block qa:for

类似 block qa:if<block/>标签上也可以使用 qa:for。例如:

<block qa:for="{{[1, 2, 3]}}">
  <view> {{index}}: </view>
  <view> {{item}} </view>
</block>
1
2
3
4

# qa:key

当列表中项目的位置可能发生变化或者项目有增减的情况下,需要给列表中项目添加唯一标识 qa:key, 以便准确渲染每一个项目的特征和状态。

qa:key 的值支持以下两种形式:

  1. 字符串:代表在 qa:for 循环列表中 item 的某个属性,该属性的值需要是在列表中唯一的字符串或者数字,且不能动态改变。
  2. 保留关键字 *this: 代表在 qa:for 循环中的 item 本身,这种情况下需要 item 本身是列表中唯一的字符串或者数字,如:[1, 2, 3]

如果列表是静态的,则可以不用添加 qa:key

示例代码:

<view>
  <switch qa:for="{{arrayData}}" qa:key="unique" style="display: block;"> {{item.id}} </switch>
  <button bindtap="unshift">Add to the front</button>

  <switch qa:for="{{numberArray}}" qa:key="*this" style="display: block;"> {{item}} </switch>
  <button bindtap="unshiftNumber">Add to the front</button>
</view>
1
2
3
4
5
6
7
Page({
  data: {
    arrayData: [
      { id: 5, unique: 'unique_5' },
      { id: 4, unique: 'unique_4' },
      { id: 3, unique: 'unique_3' },
      { id: 2, unique: 'unique_2' },
      { id: 1, unique: 'unique_1' },
      { id: 0, unique: 'unique_0' }
    ],
    numberArray: [1, 2, 3, 4]
  },
  unshift: function(e) {
    const length = this.data.arrayData.length
    this.data.arrayData = [{ id: length, unique: 'unique_' + length }].concat(this.data.arrayData)
    this.setData({
      arrayData: this.data.arrayData
    })
  },
  unshiftNumber: function(e) {
    this.data.numberArray = [this.data.numberArray.length + 1].concat(this.data.numberArray)
    this.setData({
      numberArray: this.data.numberArray
    })
  }
})
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26

在线客服