做(zuò)自(zì)由與創造的先行(xíng)者

列表渲染

小程序開(kāi)發手冊

在組件上(shàng)使用 wx:for 控制屬性綁定一(yī)個數(shù)組,即可(kě)使用數(shù)組中各項的數(shù)據重複渲染該組件。默認數(shù)組的當前項的下(xià)标變量名默認為(wèi) index,數(shù)組當前項的變量名默認為(wèi) item

代碼清單2-13 列表渲染示例

<!-- array 是一(yī)個數(shù)組 -->

<view wx:for="{{array}}">

{{index}}: {{item.message}}

</view>

<!-- 對應的腳本文件

Page({

data: {

array: [{

message: 'foo',

}, {

message: 'bar'

}]

}

})

-->

使用 wx:for-item 指定數(shù)組當前元素的變量名,使用 wx:for-index 指定數(shù)組當前下(xià)标的變量名:

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

{{idx}}: {{itemName.message}}

</view>

類似 block wx:if ,也可(kě)以将 wx:for 用在 <block/> 标簽上(shàng),以渲染一(yī)個包含多節點的結構塊。例如(rú):

<block wx:for="{{[1, 2, 3]}}">

<view> {{index}}: </view>

<view> {{item}} </view>

</block>

如(rú)果列表中項目的位置會動态改變或者有新的項目添加到列表中,并且希望列表中的項目保持自(zì)己的特征和(hé)狀态(如(rú) <input/> 中的輸入內(nèi)容, <switch/> 的選中狀态),需要(yào)使用 wx:key 來指定列表中項目的唯一(yī)的标識符。

wx:key 的值以兩種形式提供:

字符串,代表在 for 循環的 array 中 item 的某個 property,該 property 的值需要(yào)是列表中唯一(yī)的字符串或數(shù)字,且不能(néng)動态改變。

保留關鍵字 this 代表在 for 循環中的 item 本身,這(zhè)種表示需要(yào) item 本身是一(yī)個唯一(yī)的字符串或者數(shù)字,如(rú):

當數(shù)據改變觸發渲染層重新渲染的時(shí)候,會校正帶有 key 的組件,框架會确保他(tā)們被重新排序,而不是重新創建,以确保使組件保持自(zì)身的狀态,并且提高列表渲染時(shí)的效率。

代碼清單2-14 使用 wx:key 示例(WXML)

<switch wx:for="{{objectArray}}" wx:key="unique" > {{item.id}} </switch>

<button bindtap="switch"> Switch </button>

<button bindtap="addToFront"> Add to the front </button>

<switch wx:for="{{numberArray}}" wx:key="*this" > {{item}} </switch>

<button bindtap="addNumberToFront"> Add Number to the front </button>

代碼清單2-15 使用 wx:key 示例(JavaScript)

Page({

data: {

objectArray: [

{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]

},

switch: function(e) {

const length = this.data.objectArray.length

for (let i = 0; i < length; ++i) {

const x = Math.floor(Math.random() * length)

const y = Math.floor(Math.random() * length)

const temp = this.data.objectArray[x]

this.data.objectArray[x] = this.data.objectArray[y]

this.data.objectArray[y] = temp

}

this.setData({

objectArray: this.data.objectArray

})

},

addToFront: function(e) {

const length = this.data.objectArray.length

this.data.objectArray = [{id: length, unique: 'unique_' + length}].concat(this.data.objectArray)

this.setData({

objectArray: this.data.objectArray

})

},

addNumberToFront: function(e){

this.data.numberArray = [ this.data.numberArray.length + 1 ].concat(this.data.numberArray)

this.setData({

numberArray: this.data.numberArray

})

}

})

網站建設開(kāi)發|APP設計開(kāi)發|小程序建設開(kāi)發
下(xià)一(yī)篇:模闆
上(shàng)一(yī)篇:條件邏輯