uni-App 实现收藏功能
1.分析
分析
当用户点击收藏按钮时,首先判断该商品是否已近收藏过了。
若收藏过了则将该商品从缓存中删除,并将iscollect 设置为false
若未收藏则将数据添加到缓存中并将iscollect 设置为true
2.收藏按钮
通过三元运算符来判断收藏图标的变化。通过isCollect判断true或false
<view class="good_collect" @click="collect(detailList.goods_id)">
<image :src="isCollect?yesurl:nourl" mode="widthFix"></image>
<text>收藏</text>
</view>
3.点击事件
首先拿到缓存中的数据,通过findIndex()函数判断缓存中数据的goods_id是否和页面中的goods_id是否相等。若相等则传回index值大1则说明缓存中存在数据,调用点击事件应该要删除数组的数据splice(),否则通过push()添加数据,并将isCollect设置为true。
collect(){
let collect=wx.getStorageSync('collect')||[]
let index=collect.findIndex(v=>v.goods_id===this.goodInfo.goods_id)
if(index!=-1){
collect.splice(index,1)
uni.showToast({
icon:'none',
title:'取消收藏'
})
}else{
uni.showToast({
icon:'none',
title:'收藏成功'
})
collect.push(this.goodInfo)
}
this.isCollect=!this.isCollect
uni.setStorageSync('collect',collect)
}