全部產品
Search
文件中心

Mobile Platform as a Service:列表渲染

更新時間:Jul 13, 2024

a:for

在組件上使用 a:for 屬性可以綁定一個數組,即可使用數組中各項的資料重複渲染該組件。

數組當前項的下標變數名預設為 index,數組當前項的變數名預設為 item

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

使用 a:for-item 可以指定數組當前元素的變數名。使用 a:for-index 可以指定數組當前下標的變數名。

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

a:for 支援嵌套。以下是九九乘法表的嵌套範例程式碼。

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

block a:for

block a:if 類似,可以將 a:for 用在 <block/> 標籤上,以渲染一個包含多節點的結構塊。

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

a:key

如果清單項目位置會動態改變或者有新專案添加到列表中,同時希望清單項目保持特徵和狀態(比如 <input/> 中的輸入內容,<switch/> 的選中狀態),需要使用 a:key 來指定清單項目的唯一標識。

a:key 的值以兩種形式來提供:

  • 字串:代表清單項目某個屬性,屬性值需要是列表中唯一的字串或數字,比如 ID,並且不能動態改變。

  • 保留關鍵字 *this,代表清單項目本身,並且它是唯一的字串或者數字,比如當資料改變觸發重新渲染時,會校正帶有 key 的組件,架構會確保他們重新被排序,而不是重新建立,這可以使組件保持自身狀態,提高列表渲染效率。

說明

  • 如不提供 a:key,會報錯。

  • 如果明確知道列表是靜態,或者不用關注其順序,則可以忽略。

範例程式碼:

<view class="container">
  <view a:for="{{list}}" a:key="*this">
    <view onTap="bringToFront" data-value="{{item}}">
    {{item}}: click to bring to front
    </view>
  </view>
</view>
Page({
  data:{
    list:['1', '2', '3', '4'],
  },
  bringToFront(e) {
    const { value } = e.target.dataset;
    const list = this.data.list.concat();
    const index = list.indexOf(value);
    if (index !== -1) {
      list.splice(index, 1);
      list.unshift(value);
      this.setData({ list });
    }
  },
});

key

key 是比 a:key 更通用的寫法,裡面可以填充任意運算式和字串。

說明

key 不能設定在 block 上。

範例程式碼:

<view class="container">
  <view a:for="{{list}}" key="{{item}}">
    <view onTap="bringToFront" data-value="{{item}}">
    {{item}}: click to bring to front
    </view>
  </view>
</view>
Page({
  data:{
    list:['1', '2', '3', '4'],
  },
  bringToFront(e) {
    const { value } = e.target.dataset;
    const list = this.data.list.concat();
    const index = list.indexOf(value);
    if (index !== -1) {
      list.splice(index, 1);
      list.unshift(value);
      this.setData({ list });
    }
  },
});

同時可以利用 key 來防止組件複用,例如允許使用者輸入不同類型資料:

<input a:if="{{name}}" placeholder="Enter your name" />
<input a:else placeholder="Enter your email address" />

那麼當輸入 name 然後切換到 email 時,當前輸入值會保留,如果不想保留,可以加 key

<input key="name" a:if="{{name}}" placeholder="Enter your name" />
<input key="email" a:else placeholder="Enter your email address" />