Posted in Javascript onSeptember 07, 2018
本文介绍了小程序点赞收藏功能的实现代码示例,分享给大家,具体如下:
/收藏/
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,并通过循环遍历改变某个留言的点赞数,然后直接重新赋值,就能动态改变点赞数!
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。
小程序点赞收藏功能的实现代码示例
- Author -
楷楷声明:登载此文出于传递更多信息之目的,并不意味着赞同其观点或证实其描述。
Reply on: @reply_date@
@reply_contents@