微信小程序加入購物車功能


微信小程序加入購物車:https://www.bilibili.com/video/BV1nE41117BQ?p=81

// pages/goods_detail/goods_detail.js
import { getGoodsDetail } from '../../network/http.js';

Page({
  /**
   * 頁面的初始數據
   */
  data: {
    goods_id: '',
  },
  goodInfo: {},

  // 獲取商品詳情
  async getGoodsDetail() {
    const res = await getGoodsDetail(this.data.goods_id);
    const this.goodInfo = res.data.message;
  },
   // 點擊加入購物車
  addToCart() {
    //剛開始返回的是空字符串,false||[],這種返回第二個
    let cart = wx.getStorageSync('cart') || []; 
    //使用findIndex遍歷數組,找出對應項的index,否則返回-1
    let index = cart.findIndex(
      (n) => n.goods_id === this.goodInfo.goods_id
    );
    if (index === -1) {
      // 購物車中沒有此商品
      this.goodInfo.num = 1;
      cart.push(this.goodInfo);
    } else {
      cart[index].num++;
    }
    wx.setStorageSync('cart', cart);

    wx.showToast({
      title: '成功加入購物車',
      mask: true, //添加模板
    });
  },

  /**
   * 生命周期函數--監聽頁面加載
   */
  onLoad: function (options) {
    this.setData({
      goods_id: options.goods_id, //點擊商品后進入詳情頁,順便獲取商品ID
    });
    this.getGoodsDetail(); //獲取商品詳情數據
  },


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM