vue 实现收藏功能

概况

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)点击爱心图标取消/收藏图标

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值