微信小程序收藏实现及思路
- 在与页面用俩个图片来显示收藏和取消收藏,用wx:if
<image class="xiang_tu" wx:if="{{shou}}" src="/image/xiang1.png" ></image>
<image class="xiang_tu" wx:if="{{!shou}}" src="/image/xing.png" bindtap="shoucang" data-index="{{list.id}}"></image>
- 在js.data中定义一个true和false用wx:if绑定
data: {
list:[],
show: false
},
- 在js中写添加写收藏,点击图片显示收藏
// 添加收藏
shoucang(e){
let {index}=e.currentTarget.dataset
let goodsId = `${index}` //通过常是用过传参数接受的
let token = "b3a75878-f90b-4000-9694-d6bd525c7f83"
getCollect(goodsId,token).then(res=>{
// console.log("www",res)
})
this.setData({ shou: true });
}
- 有添加收藏也会有取消收藏
//取消收藏
quxiao(e){
let token = "b3a75878-f90b-4000-9694-d6bd525c7f83"
let {id} = e.e.currentTarget.dataset
getShou(token,id).then((res)=>{
this.setData({ shou: true });
})
},
- 当我们详情页点击收藏,但是当我们返回列表页在进详情页还是未收藏状态,这时我们需要检测是否收藏状态且在onLoad:页面加载的时候调用一下这个方法,让他在返回到详情页面的时候还是收藏的状态。
// 检测是否收藏
detection(){
wx.request({
url: `https://api.it120.cc/lsn/shop/goods/fav/check?token=1573f50e-5219-4845-94f0-ae95af96bbb9&goodsId=${this.data.det}`,
success:(res)=>{
// console.log("检测的",res)
if(res.data.code == 0){
this.setData({src:"/images/collect_active.png"})
}
}
})
},