Take ForComp created in components and features in pages as an example
features.json
{
"usingComponents": {
"if-comp":"/components/IfComp/IfComp",
"for-comp":"/components/ForComp/ForComp"
},
"navigationBarTitleText": "语法特点",
"navigationBarBackgroundColor": "#FFF",
"navigationBarTextStyle": "black"
}
features.wxml
<view>===========条件渲染=============</view>
<if-comp />
<view>===========循环遍历=============</view>
<for-comp />
ForComp.js
Component({
data:{
list:["a","b","c"],
stuList:[
{id:1,name:"zhang",score:90},
{id:2,name:"li",score:80},
{id:3,name:"wang",score:70},
]
}
})
ForComp.wxml
<view>--------使用默认索引、元素-------</view>
<view wx:for="{
{list}}" wx:key="*this">
索引:{
{index}} 元素:{
{item}}
</view>
<view>--------自定义索引、元素-------</view>
<view wx:for="{
{list}}" wx:key="*this" wx:for-index="idx" wx:for-item="v">
索引:{
{idx}} 元素:{
{v}}
</view>
<view wx:for="{
{stuList}}" wx:key="id">
索引:{
{index}} 元素:{
{item.id}} {
{item.name}} {
{item.score}}
</view>
Pay attention to the ws:key="" in the green box. You can refer to List Rendering | WeChat Open Documents (qq.com)
To put it simply, when the list that needs to be traversed consists of a single string, Boolean value, etc., just use *this. But when the list is composed of arrays, the key needs to select a unique feature. For example, in the stuList example above, this list is composed of multiple student information. One element contains a student's student number, name, and grades. Since names and grades may be repeated, but student IDs are not, id is chosen as the key.
running result