1. 程式人生 > >小程式點贊功能製作--列表

小程式點贊功能製作--列表

1.通過wx:if和wx:else進行圖示切換

<block wx:for="{{wishList}}" wx:key="{{index}}">
  <view class="item" data-index='{{item.id}}'>
    <view class='wish_list_box_collection' wx:if="{{item.collected==1}}">
      <!-- 點贊過 -->
      <image catchtap='onCollectionTap' src="../../images/icon/wardrobe.png" data-index='{{index}}'></image>
      <text>{{item.dzzs}}</text>
    </view>
    <view class='wish_list_box_collection' wx:else>
      <!-- 未點贊 -->
      <image src='../../images/icon/wx_app_like.png' catchtap='onCollectionTap' data-index='{{index}}'></image>
      <text>{{item.dzzs}}</text>
    </view>
  </view>
</block>

2.給兩個圖片都繫結catchtap='onCollectionTap'實踐

新增基本樣式

.item {
  padding: 20rpx;
  border: 1rpx solid red;
}

.wish_list_box_collection image {
  width: 40rpx;
  height: 40rpx;
  overflow: hidden;
}

設定初始資料collected為1,則表示已點贊;0表示未點贊,dzzs為點贊數

Page({

data: {
    wishList: [
      {dzzs: '22', collected: 1, id: 1},
      {dzzs: '33', collected: 0, id: 2},
      {dzzs: '44', collected: 1, id: 3},
      {dzzs: '555', collected: 1, id: 4},
      {dzzs: '666', collected: 0, id: 5},
      {dzzs: '777', collected: 0, id: 6}
    ],
  },
// 更改點贊狀態
  onCollectionTap: function(event) {
    // 獲取當前點選下標
    var index = event.currentTarget.dataset.index;
    // data中獲取列表
    var message = this.data.wishList;
    for (let i in message) { //遍歷列表資料
      if (i == index) { //根據下標找到目標
        var collectStatus = false
        if (message[i].collected == 0) { //如果是沒點贊+1
          collectStatus = true
          message[i].collected = parseInt(message[i].collected) + 1
          message[i].dzzs = parseInt(message[i].dzzs) + 1
        } else {
          collectStatus = false
          message[i].collected = parseInt(message[i].collected) - 1
          message[i].dzzs = parseInt(message[i].dzzs) - 1
        }
        wx.showToast({
          title: collectStatus ? '收藏成功' : '取消收藏',
        })
      }
    }
    this.setData({
      wishList: message
    })
  }