新聞中心
wx:for
在組件上使用 wx:for 控制屬性綁定一個數(shù)組,即可使用數(shù)組中各項的數(shù)據(jù)重復渲染該組件。

成都創(chuàng)新互聯(lián)主要從事網(wǎng)站建設、成都網(wǎng)站建設、網(wǎng)頁設計、企業(yè)做網(wǎng)站、公司建網(wǎng)站等業(yè)務。立足成都服務東源,10多年網(wǎng)站建設經(jīng)驗,價格優(yōu)惠、服務專業(yè),歡迎來電咨詢建站服務:028-86922220
默認數(shù)組的當前項的下標變量名默認為 index,數(shù)組當前項的變量名默認為 item
{{index}}: {{item.message}}
Page({
data: {
array: [{
message: 'foo',
}, {
message: 'bar'
}]
}
})
使用 wx:for-item 可以指定數(shù)組當前元素的變量名,
使用 wx:for-index 可以指定數(shù)組當前下標的變量名:
{{idx}}: {{itemName.message}}
如下,是一個輪播的圖片列表循環(huán),使用了wx:for方法:
這個注意了。wx:key還是要加上的,不然一直報這個提示錯誤
wx:for 也可以嵌套,下邊是一個九九乘法表
{{i}} * {{j}} = {{i * j}}
block wx:for
類似 block wx:if,也可以將 wx:for 用在標簽上,以渲染一個包含多節(jié)點的結構塊。例如:
{{index}}:
{{item}}
wx:key
如果列表中項目的位置會動態(tài)改變或者有新的項目添加到列表中,并且希望列表中的項目保持自己的特征和狀態(tài)(如 中的輸入內容, 的選中狀態(tài)),需要使用 wx:key 來指定列表中項目的唯一的標識符。
wx:key 的值以兩種形式提供
- 字符串,代表在 for 循環(huán)的 array 中 item 的某個 property,該 property 的值需要是列表中唯一的字符串或數(shù)字,且不能動態(tài)改變。
- 保留關鍵字
*this代表在 for 循環(huán)中的 item 本身,這種表示需要 item 本身是一個唯一的字符串或者數(shù)字,如:
當數(shù)據(jù)改變觸發(fā)渲染層重新渲染的時候,會校正帶有 key 的組件,框架會確保他們被重新排序,而不是重新創(chuàng)建,以確保使組件保持自身的狀態(tài),并且提高列表渲染時的效率。
如不提供 wx:key,會報一個 warning, 如果明確知道該列表是靜態(tài),或者不必關注其順序,可以選擇忽略。
示例代碼:
{{item.id}}
{{item}}
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
})
}
})
注意:
當 wx:for 的值為字符串時,會將字符串解析成字符串數(shù)組
{{item}}
等同于
{{item}}
注意: 花括號和引號之間如果有空格,將最終被解析成為字符串
{{item}}
等同于
{{item}}
網(wǎng)頁名稱:創(chuàng)新互聯(lián)小程序教程:微信小程序列表渲染wx:for
本文來源:http://www.dlmjj.cn/article/djiicii.html


咨詢
建站咨詢
