微信小程序类似于点赞取消点赞计数功能

这个方法写的是单篇文章的功能,有需要那种用于后台返回多条数据列表的点赞功能可以给我留言,大家探讨

这个功能写的目前是个假数据,直接上代码

html

<view wx:for="{{shoucang}}" wx:key="{{index}}" data-index='{{item.id}}'>
<view wx:if="{{item.collected==1}}">
<icon catchtap='onCollectionTap1' data-index='{{index}}' style="font-size:19px" class="iconfont iconshoucang2"></icon>
<text class="text">收藏</text>
</view>
<view wx:else>
<icon catchtap='onCollectionTap1' data-index='{{index}}' style="font-size:19px;color:red;" class="iconfont iconshoucang1"></icon>
<text class="text">{{item.dzzs}}</text>
</view>
</view>
 
js中的data
shoucang: [{ dzzs: '22', collected: 1, id: 1 }],
 
js
 
// 更改点赞状态
onCollectionTap1: function (event) {
// 获取当前点击下标
var index = event.currentTarget.dataset.index;
// data中获取列表
var shoucang = this.data.shoucang;
for (let i in shoucang) { //遍历列表数据
if (i == index) { //根据下标找到目标
var collectStatus = false
if (shoucang[i].collected == 0) { //如果是没点赞+1
collectStatus = true
shoucang[i].collected = parseInt(shoucang[i].collected) + 1
shoucang[i].dzzs = parseInt(shoucang[i].dzzs) + 1
} else {
collectStatus = false
shoucang[i].collected = parseInt(shoucang[i].collected) - 1
shoucang[i].dzzs = parseInt(shoucang[i].dzzs) - 1
}
wx.showToast({
title: collectStatus ? '取消收藏' : '收藏成功',
})
}
}
this.setData({
shoucang: shoucang
})
},
 

猜你喜欢

转载自www.cnblogs.com/lishuang2243/p/11069851.html