uniapp 渲染层点赞处理

本文介绍了在小程序中实现点赞功能的详细步骤,包括通过遍历后台数据集获取已点赞的ID并存储到缓存,以及点赞和取消点赞的逻辑处理。在用户点击点赞按钮时,会检查用户是否已点赞,然后相应地增加或减少点赞数,并更新数据状态。同时,点赞状态的变化也会同步更新到本地存储。
摘要由CSDN通过智能技术生成

效果图
在这里插入图片描述
一,template区域

				<!--点赞、评论区-->
				<view>
					<view style="float:right; padding-right:40rpx;">
						<image class="zan" v-if="item.like_flag==0" src="../../static/zan.png" mode="aspectFill" @click="zan" :data-zanid="item.groupID"></image>
						<image class="zan" v-else src="../../static/zan1.png" mode="aspectFill" @click="zan" :data-zanid="item.groupID"></image>
						<text> {{item.likes}} </text>							
						<image class="ping" src="../../static/ping.png" mode="aspectFill"></image>
						<image class="del" src="../../static/delete.png" mode="aspectFill" @click="del" 
							   :data-delid="index" :data-deluserid="item.userid" :data-delgroupid="item.groupID"></image>						
					</view>
				</view>

二,script区域

						//对后台返回的数据集进行遍历,拿到所有已经点过赞的id					
						var tempid=[]
						for(var i=0;i < that.grouplist.length;i++) {
							if(that.grouplist[i].like_flag==1) {    //根据自己的数据字段找到到已经点赞的								
								tempid = tempid.concat(that.grouplist[i].groupID)
							}
						}						
						uni.setStorageSync('zan', tempid)  //把点赞的数据保存到缓存

			// 点赞
			zan:function(e) {
				var zanid = e.currentTarget.dataset.zanid
				this.zangroupid = zanid				
				this.zan0(zanid)
			},			
			//点赞处理函数    
			zan0:function(item_id){			    
			    var cookie_id=uni.getStorageSync('zan')||[]  //从缓存中读取点赞的数据
			    for (var i = 0; i < this.grouplist.length;i++) {
					if (this.grouplist[i].groupID==item_id) {  //在数据列表中找到当前对应的id
						var num=this.grouplist[i].likes      //当前点赞数量
						if (cookie_id.includes(item_id)) {    //已经点过赞了,取消点赞
							for(var j in cookie_id){
								if(cookie_id[j]==item_id) {
								  cookie_id.splice(j,1)  //删除取消点赞的id
								}
							}
							--num  //点赞数减1						
							this.grouplist[i].likes = num     //更新点赞数量    
							this.grouplist[i].like_flag = 0    //我的数据中 0 是未点赞						
							uni.setStorageSync('zan', cookie_id)
						} else { //点赞操作			          
							++num    //点赞数加1						
							this.grouplist[i].likes = num      //更新点赞数量   
							this.grouplist[i].like_flag = 1    //我的数据中 1 是点赞						
							cookie_id.unshift(item_id)   //新增点赞的id
							uni.setStorageSync('zan', cookie_id)
						}
  • 2
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值