列表渲染
bind:for
/bind:for-items
在组件上使用 bind:for/bind:for-items 控制属性绑定一个数组,即可使用数组中各项的数据重复渲染该组件。
默认数组的当前项的下标变量名为 index,数组当前项的变量名默认为 item, bind:for/bind:for-items 可嵌套。
<view bind:for="{{array}}">
{{index}}: {{item.message}}
</view>
Page({
data: {
array: [
{
message: "foo",
},
{
message: "bar",
},
],
},
});
使用 bind:for-item 可以指定数组当前元素的变量名,
使用 bind:for-index 可以指定数组当前下标的变量名:
<view bind:for="{{array}}" bind:for-item="item" bind:for-index="id" >
{{id}}: {{item}.message}}
</view>
block bind:for
/bind:for-items
类似 block bind:if,也可以将 bind:for 用在
<block bind:for="{{[1, 2, 3]}}">
<view> {{index}}: </view>
<view> {{item}} </view>
</block>
bind:key
如果列表中项目的位置会动态改变或者有新的项目添加到列表中,并且希望列表中的项目保持自己的特征和状态,需要使用 bind:key 来指定列表中项目的唯一的标识符。
bind:key 的值以两种形式提供
字符串,代表在 for 循环的 array 中 item 的某个 property,该 property 的值需要是列表中唯一的字符串或数字,且不能动态改变。 保留关键字 *this 代表在 for 循环中的 item 本身,这种表示需要 item 本身是一个唯一的字符串或者数字,如: 当数据改变触发视图层重新渲染的时候,会校正带有 key 的组件,框架会确保他们被重新排序,而不是重新创建,以确保使组件保持自身的状态,并且提高列表渲染时的效率。
如不提供 bind:key,会报一个 warning, 如果明确知道该列表是静态,或者不必关注其顺序,可以选择忽略。
示例代码:
<switch bind:for="{{objectArray}}" bind:key="id" style="display: block;"> {{item.id}} </switch>
<switch bind:for="{{array}}" bind:key="*this" style="display: block;"> {{item}} </switch>
Page({
data: {
objectArray: [
{ id: 5 },
{ id: 4 },
{ id: 3 },
{ id: 2 },
{ id: 1 },
{ id: 0 },
],
array: [1, 2, 3, 4],
},
});
注意:
当 bind:for 的值为字符串时,会将字符串解析成字符串数组
<view bind:for="array">
{{item}}
</view>
等同于:
<view bind:for="{{['a','r','r','a','y']}}">
{{item}}
</view>
注意: 花括号和引号之间如果有空格,将最终被解析成为字符串
<view bind:for="{{[1,2,3]}} ">
{{item}}
</view>
等同于:
<view bind:for="{{[1,2,3] + ' '}}" >
{{item}}
</view>