样式分析:
未收藏时为灰色态,点击收藏按钮,图标变色,同时弹框实体收藏成功;
收藏成功后,点击已收藏的商品,取消收藏,此时图标恢复为灰色态,同时弹框提示取消收藏成功。
逻辑分析:
每个商品单独绑定个数据,负责管理收藏状态,点击时判断状态,然后切换。
(1)先将图片静态样式写入
因为收藏按钮是在商品展示栏上一层,所以可以用绝对定位到右下角,此时点击便不会跳页。
.goodsArea{
width: 100%;
height: auto;
display: flex;
justify-content: space-around;
flex-wrap: wrap;
}
.goodBox{
width: 45%;
position: relative;
}
.goods{
width: 100%;
height: 400rpx;
margin:20rpx 0 0 0;
position: relative;
}
/* 实现移动端的1px */
.goods::after{
content: "";
width: 200%;
height: 200%;
border: 1px solid #ddd;
transform: scale(0.5,0.5);
transform-origin:0 0;
position: absolute;
left: 0;
top: 0rpx;
}
.goods image{
width: 100%;
height: 320rpx;
display: block;
}
.goods view{
height: 80rpx;
text-align: center;
line-height: 80rpx;
}
.goodBox image.star{
position: absolute;
right: 5rpx;
bottom:20rpx;
width: 40rpx;
height: 40rpx;
}
接下来绑定数据
改动商品收藏状态值,指向性修改商品收藏状态,添加取消收藏操作,添加用户界面反馈操作
//改动商品收藏状态值
selectFn(event){
// console.log(event.currentTarget.dataset.index); //商品索引
const goodsList = this.data.goodsList;
const _this=this;
const now_index = event.currentTarget.dataset.index; //商品索引
// 重点:先设一个变量用字符串将修改值拼接起来
goodsList.forEach(function(item,index,self){
const collectStatus = "goodsList[" + index +"].collectStatus";
// 根据索引判断元素
if (now_index==index){
if (_this.data.goodsList[index].collectStatus){
_this.setData({
[collectStatus]:false
})
// 用户反馈操作
wx.showToast({
title: '取消收藏',
duration:1000
})
}else{
_this.setData({
[collectStatus]: true
})
// 用户反馈操作
wx.showToast({
title: '收藏成功',
duration: 1000
})
}
}
})
},