天天看点

微信小程序wx:key

转自https://blog.csdn.net/qq_40095973/article/details/80332063

1:

wx:key="字符串"

这个”字符串”代表在 for 循环的 array 中 item 的某个“属性”

该“属性” 的值需要是列表中唯一的字符串或数字,且不能动态改变。

用于被遍历的组件需要多个属性的时候。

//test.js
data: {
input_data: [
{ id: 1, unique: "unique1" },
{ id: 2, unique: "unique2" },
{ id: 3, unique: "unique3" },
{ id: 4, unique: "unique4" },
]
}

//test.wxml
<input value="id:{{item.id}}" wx:for="{{input_data}}" wx:key="unique" />
           

2:

wx:key="*this"

保留关键字”*this”代表在 for 循环中的 item 本身,

这种表示需要 item 本身是一个唯一的字符串或者数字

用于组件仅需要一个属性,且属性值唯一。

//test.js
data: {
numberArray: [1, 2, 3, 4],
stringArray:['aaa','ccc','fff','good']
}
//test.wxml
<input value="id:{{ item }}" wx:for="{{numberArray}}" wx:key="*this" />
<input value="id:{{ item }}" wx:for="{{stringArray}}" wx:key="*this" />