当前位置: 移动技术网 > IT编程>开发语言>JavaScript > 微信小程序基于本地缓存实现点赞功能的方法

微信小程序基于本地缓存实现点赞功能的方法

2018年02月22日  | 移动技术网IT编程  | 我要评论

本文实例讲述了微信小程序基于本地缓存实现点赞功能的方法。分享给大家供大家参考,具体如下:

wxml中的写法

注意:

1. 使用wx:if="{{condition}}" wx:else实现图标的切换效果;
2. 为图片绑定点击事件bindtap="tocollect",两个image标签都要绑定!

<image wx:if="{{collection}}" src="/images/icon/pic1.png" bindtap="tocollect"></image>
<image wx:else src="/images/icon/pic2.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;
  // 重新设置缓存
  wx.setstoragesync('cache_key',cache);
  // 更新数据绑定,从而切换图片
  this.setdata({
   // collection 默认的是 false
   collection: currentcache
  });
  // 交互反馈
  wx.showtoast({
   title: currentcache?'点赞':'取消',
   icon: 'success',
   duration: 2000
  });
 }
})

js中操作反馈—wx.showmodal的写法:

// 点击图片的点赞事件 这里使用的是同步的方式
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: "点赞"
  content: currentcache?"要点赞吗?":"要取消赞吗?",
  showcancel: "true",
  canceltext: "取消",
  cancelcolor: "#666",
  confirmtext: "确定",
  confirmcolor: "#222",
  success: function(res) {
   if (res.confirm) {
    // 重新设置缓存
    wx.setstoragesync('cache_key',cache);
    // 更新数据绑定,从而切换图片
    that.setdata({
     collection: currentcache
    })
   }
  }
 })
}

希望本文所述对大家微信小程序开发有所帮助。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网