教程接微信小程序开发教程(基础篇)7-数据绑定上,当需要展示一组数据时,可以使用wx:for
//.wxml <view wx:for="{{array}}"> {{index}}: {{item.message}} </view> //.js age({ data: { array: [{ message: 'foo', }, { message: 'bar' }] } }) |
其中index是当前数据索引的默认变量名,item是当前数据项的默认变量名。
也可以使用 wx:for-item 和 wx:for-index 来指定别名
<view wx:for="{{array}}" wx:for-index="idx" wx:for-item="itemName"> {{idx}}: {{itemName.message}} </view> 也可以嵌套使用,如下面是一个九九乘法表 <view wx:for="{{[1, 2, 3, 4, 5, 6, 7, 8, 9]}}" wx:for-item="i"> <view wx:for="{{[1, 2, 3, 4, 5, 6, 7, 8, 9]}}" wx:for-item="j"> <view wx:if="{{i <= j}}"> {{i}} * {{j}} = {{i * j}} </view> </view> </view> |
类似block wx:if,也可以将wx:for用在
<block wx:for="{{[1, 2, 3]}}"> <view> {{index}}: </view> <view> {{item}} </view> </block> |
wx:key
要理解为什么需要wx:key,先来看一个例子:
//.wxml <checkbox wx:for="{{objectArray}}" value="{{item.name}}" style="display: block;"> {{item.name}} </checkbox> <button bindtap="addToFront">在上方添加一个新的check组件</button> //.js Page({ data: { objectArray: [ {id: 1, name: '我没有被选中'}, {id: 2, name: '我没有被选中'}, ], }, addToFront: function(e) { const length = this.data.objectArray.length this.data.objectArray = [{id: length, name: '我没有被选中'}].concat(this.data.objectArray) this.setData({ objectArray: this.data.objectArray }) }, }) |
上面的代码创建了两个checkbox组件和一个按钮,当点击按钮会在最上方新增一个checkbox组件。
编译代码,会显示如下界面:
点击按钮,界面如下:
ok,到这里一切正常 ,为了更好的说明问题,加入checkbox选中事件的处理,当checkbox被选中时,将文字修改为"我被选中了",相关代码如下:
//wxml <checkbox-group bindchange="checkboxChange"> <checkbox wx:for="{{objectArray}}" value="{{item.id}}" style="display: block;" > {{item.name}} </checkbox> </checkbox-group> <button bindtap="addToFront">在上方添加一个新的check组件</button> //js Page({ data: { objectArray: [ {id: 1, name: '我没有被选中'}, {id: 2, name: '我没有被选中'}, ], }, addToFront: function(e) { const length = this.data.objectArray.length this.data.objectArray = [{id: length + 1, name: '我没有被选中'}].concat(this.data.objectArray) this.setData({ objectArray: this.data.objectArray }) }, checkboxChange: function(e){ console.log('checkboxChange') const length = this.data.objectArray.length let checkBoxArray = this.data.objectArray for (let i = 0; i < length; i++) { let ischecked = false for (let j = 0; j < e.detail.value.length; j++){ if (checkBoxArray[i].id == e.detail.value[j]){ checkBoxArray[i].name = '我被选中了' ischecked = true } } if (!ischecked){ checkBoxArray[i].name = '我没有被选中' } } this.setData({ objectArray: this.data.objectArray }) } }) |
当选中第一个checkbox时,界面如下
这时如果点击添加组件按钮会怎样呢,期望的效果应该如下
然而实际效果确是下图这样的
可以看到渲染引擎并没有将选中的效果和数据绑定起来,导致出现了预期之外的结果。如果想要达到预期效果,就要使用wx:key
<checkbox-group bindchange="checkboxChange"> <checkbox wx:for="{{objectArray}}" wx:key = "id" value="{{item.id}}" style="display: block;" > {{item.name}} </checkbox> </checkbox-group> <button bindtap="addToFront">在上方添加一个新的check组件</button> 将.wxml文件修改为上述代码所示,就可以实现预期效果, |