效果图
一,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)
}