如果列表中項目的位置會動態改變或者有新的項目添加到列表中,並且希望列表中的項目保持自己的特征和狀態(如 <input/>
中的輸入內容,<switch/>
的選中狀態),需要使用 wx:key
來指定列表中項目的唯一的標識符。
wx:key
的值以兩種形式提供
- 字符串,代表在 for 循環的 array 中 item 的某個 property,該 property 的值需要是列表中唯一的字符串或數字,且不能動態改變。
- 保留關鍵字
*this
代表在 for 循環中的 item 本身,這種表示需要 item 本身是一個唯一的字符串或者數字,如:numberArray: [1, 2, 3, 4]
wxml文件:
<view class="userList" wx:for="{{items}}" wx:key="{{item.userId}} wx:for-index="idx""> <view class="{{userCellId==idx?'userCellActive':'userCell'}}" data-idx="{{idx}}" bindtap="userListAction">{{item.name}}</view> </view>
1、page.data里設一個變量,比如userCellId(JS文件在下面👇)
2、列表項里增加一個屬性data-id="{{idx}}"
3、在列表項的userListAction事件里this.setData({userCellId: e.target.dataset.idx})
4、列表項的class里根據userCellId設置不同樣式,如class="{{userCellId==idx?'userCellActive':'userCell'}}"
5、wxss里定義.userCellActive和.userCell樣式的背景顏色。
JS文件
Page({
data:{
items:[
{
userId: 1, name: "user1", }, { userId: 2, name: "user2", }, { userId: 3, name: "user3", } ], userCellId: 0 }, userListAction:function(e){
console.log(`點擊了${e.target.dataset.idx}`) this.setData({ userCellId: e.target.dataset.idx }) } })
wxss文件
.userCell{ background-color: red; } .userCellActive{ background-color: green; }