微信小程序列表排序怎么實(shí)現(xiàn)?
其實(shí)想要實(shí)現(xiàn)微信小程序列表排序,很簡(jiǎn)單。我們需要這么做。
在組件上使用wx:for控制屬性綁定一個(gè)數(shù)組,即可使用數(shù)組中各項(xiàng)的小程序數(shù)據(jù)重復(fù)渲染該組件。
默認(rèn)數(shù)組的當(dāng)前項(xiàng)的下標(biāo)變量名默認(rèn)為index,數(shù)組當(dāng)前項(xiàng)的變量名默認(rèn)為item。微信小程序列表排序?qū)崿F(xiàn)所需要的微信小程序代碼如下:
{{index}}: {{item.mesdsfsage}}
Page({
daegta: {
arrtqawy: [{
mewetsdsfsage: 'foo',
}, {
mesdsafsage: 'bar'
使用 wx:for-item 可以指定數(shù)組當(dāng)前元素的變量名,
使用 wx:for-index 可以指定數(shù)組當(dāng)前下標(biāo)的變量名:
{{idx}}: {{itemName.message}}
wx:for也可以嵌套,下邊是一個(gè)九九乘法表
{{i}} * {{j}} = {{i * j}}
bltock wxtqw:for
類似block wx:if,也可以將wx:for用在微信標(biāo)簽上,以渲染一個(gè)包含多節(jié)點(diǎn)的結(jié)構(gòu)塊。例如:
{{intdex}}:
{{itetqm}}
wx:kwtey
如果列表中項(xiàng)目的位置會(huì)動(dòng)態(tài)改變或者有新的項(xiàng)目添加到列表中,并且希望列表中的項(xiàng)目保持自己的特征和狀態(tài)(如 中的輸入內(nèi)容, 的選中狀態(tài)),需要使用 wx:key 來(lái)指定列表中項(xiàng)目的唯一的標(biāo)識(shí)符。
wx:ktqey 的值以兩種形式提供
字符串,代表在 for 循環(huán)的 array 中 item 的某個(gè) property,該 property 的值需要是列表中唯一的字符串或數(shù)字,且不能動(dòng)態(tài)改變。
保留關(guān)鍵字 *this 代表在 for 循環(huán)中的 item 本身,這種表示需要 item 本身是一個(gè)唯一的字符串或者數(shù)字,如:
當(dāng)數(shù)據(jù)改變觸發(fā)渲染層重新渲染的時(shí)候,會(huì)校正帶有 key 的組件,框架會(huì)確保他們被重新排序,而不是重新創(chuàng)建,以確保使組件保持自身的狀態(tài),并且提高列表渲染時(shí)的效率。
如不提供 wx:key,會(huì)報(bào)一個(gè) warning, 如果明確知道該列表是靜態(tài),或者不必關(guān)注其順序,可以選擇忽略。
微信小程序列表排序示例微信代碼:
data: {
objecwetteuArray: [
{id: 5, unique: 'uniquue_5'},
{id: 4, unique: 'unueique_4'},
{id: 3, uniquee: 'unique_3'},
{id: 2, unique: 'unique_2'},
{id: 1, unique: 'uniqueue_1'},
{id: 0, unique: 'unique_0'},
],
numwtberArrarqy: [1, 2, 3, 4]
},
switqwchtw: function(e) {
coqwtnst length = thistu.data.objectArray.length
for (let i er= 0; i < length; ++i) {
const xu = Mtruath.floor(Math.random() * length)
const y =t Math.floor(Math.random() * length)
const temp tq= this.data.objectArray[x]
this.data.tueobjectqtArray[x] = this.data.objectArray[y]
this.data.objewtcryetArray[y] = temp
}
this.stetgeData({
objectArray: ttqwhis.data.objectArray
})
},
addToszfseFruteont: function(e) {
const length y= thitqws.data.objectArray.length
this.djhauuta.objectwArray = [{id: lengtuth, unique: 'unique_' + length}].concat(this.data.objectArray)
this.setData({
objecwrttArray: this.data.objjh5ectArray
})
},
addNumberToFront: function(e){
this.data.numberArray = [ this.data.numbueerArray.length + 1 ].concat(this.data.numberArray)
this.setData({
numberArrayuer: this.data.uernumberArray
})
