小程序点赞收藏功能的实现代码示例
程序员文章站
2023-12-03 18:02:46
本文介绍了小程序点赞收藏功能的实现代码示例,分享给大家,具体如下:
/收藏/
focusfavoritetab: function (e) {
var t...
本文介绍了小程序点赞收藏功能的实现代码示例,分享给大家,具体如下:
/收藏/
focusfavoritetab: function (e) { var that = this; var isfocus = that.data.isfocus; console.log("isfocus", isfocus) var itemid = that.data.itemid; if (isfocus) { favoriteservice.cancel(that, itemid).then((res) => { wx.showtoast({ title: "取消收藏", icon: 'success', duration: 1000 }); this.setdata({ isfocus: false, }); }) } else { favoriteservice.add(that, itemid).then((res) => { wx.showtoast({ title: res.data == 1 ? "收藏成功" : "收藏失败", icon: 'success', duration: 1000 }); this.setdata({ isfocus: true, }); }); } },
/点赞/
focusliketab: function (e) { var that = this; var islike = that.data.islike; let itemdetail = this.data.itemdetail var itemid = that.data.itemid; if (islike) { itemservice.cancellike(that, itemid).then((res) => { wx.showtoast({ title: "点赞取消", icon: 'success', duration: 1000 }); itemdetail.liked--; this.setdata({ itemdetail:itemdetail }); this.setdata({ islike: false, }); }) } else { itemservice.addlike(that, itemid).then((res) => { wx.showtoast({ title: res.data == 1 ? "点赞成功" : "点赞失败", icon: 'success', duration: 1000 }); itemdetail.liked++; this.setdata({ itemdetail: itemdetail }); this.setdata({ islike: true, }); }); } },
取消点赞功能
/*更新点赞*/ update_zan:function(e){ var that = this; var data = e.currenttarget.dataset; var mid = data.mid; var cookie_mid = wx.getstoragesync('zan') || [];//获取全部点赞的mid var isadd = 1; var newmessage = []; if (cookie_mid.includes(mid)){//说明已经点过赞,取消赞 isadd = 0; var m = 0; for (var j in cookie_mid){ if(cookie_mid[j] != mid){ newmessage[m] = cookie_mid[j]; m++ } } wx.setstoragesync('zan', newmessage);//删除取消赞的mid }else{ cookie_mid.unshift(mid); wx.setstoragesync('zan', cookie_mid);//新增赞的mid } wx.request({ url: app.globaldata.api.api_system, data: { action: 'zannum', mid: mid, isadd: isadd, wxid: app.globaldata.wxid }, method: 'get', // header: {}, success: function (res) { var message = that.data.message; for (var i in message) { if(message[i].mid == mid){ if(isadd){ message[i].zan = parseint(message[i].zan) + 1 }else{ message[i].zan = parseint(message[i].zan) - 1 } } } that.setdata({ message: message }) } })
重点注意代码:
(1)要把所有已经点过赞的留言id给存储到本地缓存之中,这样如果重复点赞的,就可以判断出来,并取消点赞,取消点赞的同时要去掉缓存中的id;
(2)新增点赞和取消点赞用到同一个api,通过isadd=1或者isadd=0来判断是新增还是取消点赞
(3)为了不频繁去读取留言列表,可以直接调用this.data.message,并通过循环遍历改变某个留言的点赞数,然后直接重新赋值,就能动态改变点赞数!
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。