1. 程式人生 > >微信小程序之點贊和取消點贊

微信小程序之點贊和取消點贊

技術分享 tex 所有 gets highlight false modal log set

技術分享圖片技術分享圖片

wxml代碼

<image wx:if="{{collection}}" src="/images/boy.png"  bindtap="toCollect"></image>
<image wx:else src="/images/girl.png" bindtap="toCollect"></image>


切換圖片

js代碼

Page({
  data: {
  },
  onLoad: function (option) {
    // 獲取接收到的id值
    var getId = option.id;
    // 讓接收到的id值傳遞到data:{}裏面
    // this.setData({
    //   currentId: getId
    // });
    // 讀取所有的文章列表點贊緩存狀態
    var cache = wx.getStorageSync(‘cache_key‘);
    // 如果緩存狀態存在
    if (cache) {
      // 拿到所有緩存狀態中的1個
      var currentCache = cache[getId];
      // 把拿到的緩存狀態中的1個賦值給data中的collection,如果當前文章沒有緩存狀態,currentCache 的值就是 false,如果當前文章的緩存存在,那麽 currentCache 就是有值的,有值的說明 currentCache 的值是 true
      this.setData({
        collection: currentCache
      })
    } else {
      // 如果所有的緩存狀態都不存在 就讓不存在的緩存存在
      var cache = {};
      // 既然所有的緩存都不存在,那麽當前這個文章點贊的緩存也不存在,我們可以把當前這個文章點贊的緩存值設置為 false
      cache[getId] = false;
      // 把設置的當前文章點贊放在整體的緩存中
      wx.setStorageSync(‘cache_key‘, cache);
    }
  },
  // 點擊圖片的點贊事件  這裏使用的是同步的方式
  toCollect: function (event) {
    // 獲取緩存,得到當前文章是否被點贊
    var cache = wx.getStorageSync(‘cache_key‘);
    // 獲取當前文章是否被點贊的緩存
    var currentCache = cache[this.data.currentId];
    // 取反,點贊的變成未點贊 未點贊的變成點贊
    currentCache = !currentCache;
    // 更新cache中的對應的1個的緩存值,使其等於當前取反的緩存值
    cache[this.data.currentId] = currentCache;
    // 調用 showModal方法
    this.showModal(cache, currentCache);
  },
  showModal: function (cache, currentCache) {
    var that = this;
    wx.showModal({
      title: "2222步",
      content: currentCache ? "點贊" : "取消點贊",
      showCancel: false,
      // cancelText: "取消111",
      // cancelColor: "#000",
      confirmText: "知道啦",
      confirmColor: "#0f0",
      success: function (res) {
        console.log(res)
        if (res.confirm) {
          // 重新設置緩存
          wx.setStorageSync(‘cache_key‘, cache);
          // 更新數據綁定,從而切換圖片
          that.setData({
            collection: currentCache
          })
        }
      }
    })
  }
})

  

微信小程序之點贊和取消點贊