微信小程序加入购物车: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(); //获取商品详情数据
},