小程序列表渲染指南:wx:for属性详解
在微信小程序开发中,wx:for指令用于实现基于数组的列表渲染功能。通过将此属性绑定到数组上,程序会自动遍历数组元素并重复渲染对应的组件。
默认情况下,循环过程中当前项的索引变量名为index,当前项本身的变量名为item,因此在模板中可通过{{index}}和{{item}}访问这些值。
基本语法结构(以block标签为例):
<block wx:for="{{listData}}" wx:key="[String | *this]" wx:for-index="[String]" wx:for-item="[String]">
</block>
参数说明:
- wx:for 【必需参数】数组类型,用于循环渲染的数据源
- wx:for-index 【可选参数】自定义索引变量名,在嵌套循环场景下特别有用,用于区分不同层级的索引
- wx:for-item 【可选参数】自定义当前项变量名,在嵌套循环场景下特别有用,用于区分不同层级的当前项
- wx:key 【可选参数】字符串或*this,当列表需要动态添加、删除或排序项,且希望保持组件状态时必须使用
基础使用示例:
1 <view wx:for="{{itemsList}}">
2 {{index}}: {{item.content}}
3 </view>
1 Page({
2 data: {
3 itemsList: [{
4 content: '第一条信息',
5 }, {
6 content: '第二条信息'
7 }]
8 }
9 })
在上述代码中,{{index}}表示数组元素的索引值(从0开始),{{item.content}}表示数组元素中content字段的值。
渲染结果将显示为: 0:第一条信息 1:第二条信息
自定义变量名应用:
以下是一个九九乘法表示例,展示了如何使用自定义变量名避免命名冲突:
1 <view wx:for="{{[1, 2, 3, 4, 5, 6, 7, 8, 9]}}" wx:for-item="row">
2 <view wx:for="{{[1, 2, 3, 4, 5, 6, 7, 8, 9]}}" wx:for-item="col">
3 <view wx:if="{{row <= col}}">
4 {{row}} × {{col}} = {{row * col}}
5 </view>
6 </view>
7 </view>
此例中,外层循环的{{item}}被重命名为row,内层循环的{{item}}被重命名为col,有效解决了变量名冲突问题。
wx:key的重要性与应用:
当列表项目需要动态改变位置或新增项目,且希望保持组件原有状态(如输入框内容、开关状态)时,必须使用wx:key属性来指定唯一标识符。
wx:key支持两种赋值方式:
- 字符串形式:指向数组元素中的某个属性,该属性的值必须是唯一的字符串或数字,且不能动态变化。
- 保留字*this:代表数组元素本身,要求元素本身是唯一的字符串或数字。
当数据变化触发重新渲染时,框架会根据key值对组件进行重新排序而非重新创建,从而保持组件状态并提高渲染效率。
1 <checkbox wx:for="{{items}}" wx:key="id" style="display: block;"> {{item.name}} </checkbox>
2 <button bindtap="shuffleItems"> 随机排序 </button>
3 <button bindtap="addNewItem"> 添加项目 </button>
4
5 <checkbox wx:for="{{numbers}}" wx:key="*this" style="display: block;"> {{item}} </checkbox>
5 <button bindtap="addNumber"> 添加数字 </button>
1 Page({
2 data: {
3 items: [
4 {id: 1, name: '选项1'},
5 {id: 2, name: '选项2'},
6 {id: 3, name: '选项3'},
7 {id: 4, name: '选项4'},
8 ],
9 numbers: [5, 8, 13, 21]
10 },
11 shuffleItems: function() {
12 const itemsCopy = [...this.data.items];
13 for (let i = itemsCopy.length - 1; i > 0; i--) {
14 const j = Math.floor(Math.random() * (i + 1));
15 [itemsCopy[i], itemsCopy[j]] = [itemsCopy[j], itemsCopy[i]];
16 }
17 this.setData({ items: itemsCopy });
18 },
19 addNewItem: function() {
20 const newId = this.data.items.length + 1;
21 this.setData({
22 items: [{id: newId, name: `选项${newId}`}].concat(this.data.items)
23 });
24 },
25 addNumber: function() {
26 const nextNum = this.data.numbers.length > 0
27 ? this.data.numbers[this.data.numbers.length - 1] + 1
28 : 1;
29 this.setData({
30 numbers: [nextNum].concat(this.data.numbers)
31 });
32 }
33 })
在实际运行时,如果你选中某个复选框后点击"随机排序"或"添加项目"按钮,已选中的状态会保持不变。若未添加wx:key属性,选中状态将会丢失。