概况
1.首先判断这件商品是否已经收藏,向后端发起请求查询商品是否收藏。
2.点击收藏事件,像后端增加一条数据到收藏列表。
<van-action-bar-icon icon="like-o" @click="like(item)" :color="item.color"/>
//item 参数
(1)listQuery里接收后端参数,为了获取商品列表数据
data() {
return {
listQuery: {
page: 1,
limit: 40,
},
records: [
{
id: 0,
bookname: '',
price: 0,
image: ''
}
]
}
},
(2)方法调用部分
checkList()判断是否收藏(初始是收藏图标是否点亮)
like()点击时增加一条数据到收藏列表
methods: {
//点击收藏事件,向后台数据库插入一条新数据
like(data) {
//当前商品列表有参数id,使判断是否收藏接口参数book_id=records.id,item 形参所以item.id
addList({ book_id: data.id }).then((response) => {
if (response.data.data == '取消收藏成功') { //如果未收藏,收藏图标为灰色,否则为红色
data.color = 'gray'
} else {
data.color = 'red'
}
})
},
getList() {
fetchList(this.listQuery).then((response) => { //获取商品列表records数组数据
this.records = response.data.data.records
//foeEach遍历对象,e为参数相当于上方item
this.records.forEach((e) => {
checkList({ book_id: e.id }).then((response) => {
if (response.data.message) {
e.color = 'red'
} else {
e.color = 'gray'
}
})
})
})
},
}
(3)后台样式
1.获取当前商品列表接口(id)
2.判断初始页面是否收藏(book_id)
(4)点击爱心图标取消/收藏图标