a:for属性可以绑定一个数组,然后就可以使用数组中各项的数据重复渲染该组件。index,数组当前项的变量名默认为item。<view a:for="{{array}}">
{{index}}: {{item.message}}
</view>Page({
data: {
array: [{
message: 'foo',
}, {
message: 'bar'
}]
}
})a:for-item可以指定数组当前元素的变量名。a:for-index可以指定数组当前下标的变量名。<view a:for="{{array}}" a:for-index="idx" a:for-item="itemName">
{{idx}}: {{itemName.message}}
</view>a:for也可以嵌套,下边是一个九九乘法表。<view a:for="{{[1, 2, 3, 4, 5, 6, 7, 8, 9]}}" a:for-item="i">
<view a:for="{{[1, 2, 3, 4, 5, 6, 7, 8, 9]}}" a:for-item="j">
<view a:if="{{i <= j}}">
{{i}} * {{j}} = {{i * j}}
</view>
</view>
</view>block a:if,可以将a:for用在<block/>标签上,以渲染一个包含多节点的结构块。<block a:for="{{[1, 2, 3]}}">
<view> {{index}}: </view>
<view> {{item}} </view>
</block><input/> 中的输入内容,<switch/> 的选中状态),需要使用 a:key 来指定列表中项目的唯一的标识符。a:key的值以两种形式来提供。for循环的array中item的某个属性。该属性的值需要是列表中唯一的字符串或数字,并且不能动态的改变。*this,代表在for循环中的item本身,表示需要item本身是唯一的字符串或者数字,比如当数据改变触发渲染层重新执行渲染的时候,会校正带有key的组件,框架会确保他们重新被排序,而不是重新创建,确保使组件保持自身的状态,并且提高列表渲染时的效率。<view class="container">
<view a:for="{{list}}" a:key="*this">
<view onTap="bringToFront" data-value="{{item}}">
{{item}}: click to bring to front
</view>
</view>
</view>Page({
data:{
list:['1', '2', '3', '4'],
},
bringToFront(e) {
const { value } = e.target.dataset;
const list = this.data.list.concat();
const index = list.indexOf(value);
if (index !== -1) {
list.splice(index, 1);
list.unshift(value);
this.setData({ list });
}
}
});<view class="container">
<view a:for="{{list}}" key="{{item}}">
<view onTap="bringToFront" data-value="{{item}}">
{{item}}: click to bring to front
</view>
</view>
</view>Page({
data:{
list:['1', '2', '3', '4'],
},
bringToFront(e) {
const { value } = e.target.dataset;
const list = this.data.list.concat();
const index = list.indexOf(value);
if (index !== -1) {
list.splice(index, 1);
list.unshift(value);
this.setData({ list });
}
}
});<input a:if="{{name}}" placeholder="Enter your username"/>
<input a:else placeholder="Enter your email address"/><input key="name" a:if="{{name}}" placeholder="Enter your username"/>
<input key="email" a:else placeholder="Enter your email address"/>