11小程序加入购物车

导读:本篇文章讲解 11小程序加入购物车,希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com

加入购物车

detail.wxml

<!-- 加入购物车 -->
<button bindtap="handleAddCar">加入购物车</button>
<!-- 跳转到购物车 -->
<button bindtap="handleChangeCar">购物车</button>

detail.js

Page({
  data: {
    goodsInfo: {},
    users: null
  },
  // id是小程序默认或预留的属性,不能命名为id
  myid: 0,

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.myid = Number(options.id)
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    wx.request({
      url: `http://localhost:3000/goods/${this.myid}`,
      success: (res) => {
        this.setData({
          goodsInfo: res.data
        })
      }
    })
  },

  // 添加购物车
  handleAddCar () {
    // 判断是否登录
    if (wx.getStorageSync('isLogin') === true) {
      // 如果登录成功,跳转到购物车页面
      wx.request({
        url: `http://localhost:3000/carts?goodId=${this.data.goodsInfo.id}`,
        success: (res) => {
          if (res.data.length === 0) {
            console.log('post添加新商品')
            // 追加一个新的商品到购物车
            this.addCar()
          } else {
            console.log('+1')
            // 更新某商品数量 +1
            this.updateCart(res.data[0]) // [0] 是数组转换为对象
          }
        }
      })
    } else {
      // 如果登录失败,就往选项卡跳转到Center页面
      wx.switchTab({
        url: '/pages/center/center',
      })
    }
  },

  // 更新商品数量
  updateCart (cartobj) {
    wx.request({
      url: `http://localhost:3000/carts/${cartobj.id}`,
      method: 'put', // 更新
      data: {
        ...cartobj,
        number: cartobj.number + 1
      },
      success: () => {
        // 更新成功提示
        wx.showToast({
          title: '加入购物车成功', 
          icon: 'success', 
          duration: 2000 // 几秒后隐藏
        })
      }
    })
  },

  // 追加新商品
  addCar () {
      /*
        判断此商品是否存过:
        1.如果存过,就更新数据,就让该数据++操作
        2.如果没存过,就post新数据存储
      */ 
     wx.request({
      url: 'http://localhost:3000/carts',
      data: {
        // 真实工作中,要与后端商品数据结构
        goodId: this.data.goodsInfo.id, // 商品的id
        number: 1, // 加入购物车的数量
        username: wx.getStorageSync('users').nickName, // 用户昵称
        checked: false // 是否选中
      },
      method: 'post', // json-server添加一条新数据的方法
      success: (res) => {
        // 更新成功提示
        wx.showToast({
          title: '加入购物车成功', 
          icon: 'success', 
          duration: 2000 // 几秒后隐藏
        })
      }
    })
  },
    
  // 跳转到购物车
  handleChangeCar () {
    wx.switchTab({
      url: '/pages/shopCar/shopCar',
    })
  }

})

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/4555.html

(0)
小半的头像小半

相关推荐

极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!