微信小程序学习笔记-在添加购物车时,tabBar右上角会显示有几个商品

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是实现微信小程序点击加入购物车显示购物车商品数量的代码: 1. 在app.js中定义全局变量cartList,用于存放购物车商品列表 ``` App({ globalData: { cartList: [] } }) ``` 2. 在商品列表页面的wxml中添加加入购物车按钮,并绑定tap事件 ``` <view class="add-cart" bindtap="addToCart">加入购物车</view> ``` 3. 在商品列表页面的js中编写addToCart方法,将商品添加购物车列表中,并更新购物车图标上的数量 ``` const app = getApp() Page({ data: { goodsList: [...], cartCount: 0 }, addToCart(e) { const goodsId = e.currentTarget.dataset.goodsId const cartList = app.globalData.cartList const index = cartList.findIndex(item => item.id === goodsId) if (index !== -1) { cartList[index].count++ } else { cartList.push({ id: goodsId, count: 1 }) } const cartCount = cartList.reduce((sum, item) => sum + item.count, 0) this.setData({ cartCount }) } }) ``` 4. 在app.json中配置购物车页面路径和购物车图标 ``` { "pages": [ "...", "pages/cart/cart" ], "tabBar": { "list": [ { "pagePath": "pages/index/index", "text": "首页", "iconPath": "assets/tabbar/home.png", "selectedIconPath": "assets/tabbar/home_selected.png" }, { "pagePath": "pages/cart/cart", "text": "购物车", "iconPath": "assets/tabbar/cart.png", "selectedIconPath": "assets/tabbar/cart_selected.png" } ] } } ``` 5. 在购物车页面的wxml中显示购物车商品数量 ``` <view class="cart-count">{{cartCount}}</view> ``` 6. 在购物车页面的js中获取购物车商品列表,并计算购物车商品数量 ``` const app = getApp() Page({ data: { cartList: [], cartCount: 0 }, onLoad() { const cartList = app.globalData.cartList const cartCount = cartList.reduce((sum, item) => sum + item.count, 0) this.setData({ cartList, cartCount }) } }) ``` 以上就是实现微信小程序点击加入购物车显示购物车商品数量的代码。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值