收藏介绍:
收藏功能和点赞功能其实是一样的,点赞功能我们用的是后端返回的一个数组,这里就写成后端返回枚举值,逻辑其实是一样的
收藏流程:
- 给模板中收藏按钮添加点击事件
- 先判断一下如果当前商品的收藏,字段如果等于0(根据后端接口拿对应字段)没有的话就进行收藏
- 请求后端收藏接口,把当前点击收藏的id给传过去
- 最后如果请求成功了的话,就提示收藏成功
最后上代码:
<template>
<view class="content">
<!-- 收藏 -->
<text @click="collect">收藏</text>
</view>
</template>
<script>
export default {
data() {
return {
goods: {
id: '商品id',
collect: 0 || 1 // 0没有收藏,1收藏
}
}
}
methods: {
async collect() {
if(this.goods.collect === 0) {
const res = await uni.$http.get('后端接口', this.goods.id)
if(res.data.code === 200) return this.$showMsg('收藏成功')
} else if(this.goods.collect === 1) {
const res = await uni.$http.get('后端接口', this.goods.id)
if(res.data.code === 200) return this.$showMsg('取消收藏')
}
}
}
}
</script>