tags: [小程序]


普通用法

wx:key="字符串"

解释

这个”字符串”代表在 for 循环的 array 中 item 的某个“属性” 该“属性” 的值需要是列表中唯一的字符串或数字,且不能动态改变。 用于被遍历的组件需要多个属性的时候。

  1. //test.js
  2. data: {
  3. input_data: [
  4. { id: 1, unique: "unique1" },
  5. { id: 2, unique: "unique2" },
  6. { id: 3, unique: "unique3" },
  7. { id: 4, unique: "unique4" },
  8. ]
  9. }
//test.wxml
<input value="id:{{item.id}}"   wx:for="{{input_data}}"  wx:key="unique"  />

特殊用法

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"  />