微信小程序加入購物車: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(); //獲取商品詳情數據
},