微信小程序171~180
1.封装购物车接口API
import http from '@/utils/http'export const reqAddCrt = ({ goodsId, count, ...data }) => {return http.get(`/cart/addToCart/${goodsId}/${count}`, data)
}export const reqCartList = () => {return http.get('/cart/getCartList')
}export const reqUpdateChecked = ({ goodsId, isChecked }) => {return http.get(`/cart/checkCart/${goodsId}/${isChecked}`)
}export const reqCheckAllStatus = (isChecked) => {return http.get(`/cart/checkAllCart/${isChecked}`)
}export const reqDelCartGoods = (goodsId) => {return http.get(`/cart/delete/${goodsId}`)
}
2.模板分析和渲染
- 若点击加入购物车,则将当前商品加入购物车
- 若点击立即购买,要跳转到结算支付页面,立即购买
- 如果是立即购买,不支持购买多个商品
data: {goodsInfo: {},show: false,count: 1,blessing: '',buyNow: 0},// 加入购物车handleAddcart() {this.setData({show: true,buyNow: 0})},// 立即购买handeGotoBuy() {this.setData({show: true,buyNow: 1})},
3.让页面和store对象建立关联
使用BehaviorWithStore让页面和store建立关联
import { BehaviorWithStore } from 'mobx-miniprogram-bindings'
import { userstore } from '@/stores/userstore'
export const userBehavior = BehaviorWithStore({storeBindings: {store: userStore,fields: ['token']}
})
4.加入购物车和立即购买区分处理
// 监听是否更改了购买数量onChangeGoodsCount(event) {this.setData({count: Number(event.detail)})},// 确定按钮触发事件处理函数async handlerSubmit() {const { token, count, blessing, buyNow } = this.dataconst goodsId = this.goodsId// 判断用户是否进行了登录if (!token) {wx.navigateTo({url: '/pages/login/login'})return}// 如果buynow是0,加入购物车// 如果buynow是1,立即购买if (buyNow === 0) {const res = await reqAddCart({ goodsId, count, blessing })if (res.code === 200) {wx.toast({ title: '加入购物车成功' })this.setData({show: false})}} else {wx.navigateTo({url: `/pages/order/detail/detail?goodsId=${goodsId}&blessing=${blessing}`})}}
5.展示购物车购买数量
加入购物车成功以后,重新计算购物车商品的购买数量
this.getCartCount()
// 计算商品的数量getCartCount() {// 用token判断用户是否进行了登录if(!this.data.token) return// 计算购买的数量const res = await reqCartList()// 判断购物车中是否存在商品if(res.data.length !== 0) {// 累加得出商品数量let allCount = 0res.data.forEach((item) => {allCount += item.count})this.setData({// info要求属性值为字符串类型// 而且如果购买的数量大于99,页面上显示99+allCount: ( allCount > 99 ? '99+' : allCount ) + ''})}},
6.购物车关联Store对象
import { ComponentWithStore } from 'mobx-miniprogram-bindings'
import { userStore } from '@/stores/userstore'
ComponentWithStore({storeBindings: {store: userStore,fields: ['token']},// 组件的初始数据data: {cartList: [1, 2, 3, 4],emptyDes: '还没有添加商品,快去添加吧~'},// 组件的方法列表methods: {// 如果用Component方法构建页面,声明周期写到methods中才行onShow() {console.log(this.data.token)}}
})
7.获取购物车列表数据并渲染
- 如果没有进行登录,购物车页面需要展示文案:您尚未登录,点击登录获取更多权益
- 如果用户进行登录,获取购物车列表数据
- 1:购物车没有商品,展示文案: 还没有添加商品,快去添加吧~
- 2:购物车列表有数据,需要使用数据对页面进行渲染
// 展示文案同时获取购物车列表数据async showTipGetList() {const { token } = this.dataif (!token) {this.setData({emptyDes: '您尚未登录,点击登录获取更多权益',cartList: []})return}// 如果登录,获取数据const { code, data, cartList } = await reqCartList()if (code === 200) {this.setData({cartList,emptyDes: cartList.length === 0 && '还没有添加商品,快去添加吧~'})}},// 如果用Component方法构建页面,声明周期写到methods中才行onShow() {this.showTipGetList()}}
8.更新商品的购买状态
获取商品的最新状态并同步到服务器
// 更新商品的购买状态async updateChecked(event) {// 获取最新购买状态const { detail } = event// 获取传递的商品id及索引const { id, index } = event.target.dataset// 将最新的购买状态转化为后端需要的0和1const isChecked = detail ? 1 : 0const res = await reqUpdateChecked(id, isChecked)if (res.code === 200) {// 找到对应索引的商品更改购买状态this.setData({[`cartList[${index}].isChecked`]: isChecked})}},
9.控制全选按钮的选中状态
基于购物车列表中已有的数据,产生一个新数据,控制全选按钮的选中效果,可以使用计算属性来实现
npm install --save miniprogram-computed
// 定义计算属性,控制全选按钮的选中效果computed: {//computed中不能用this访问data的数据selectAllStatus(data) {// 如果购物车里有商品在进行计算return data.cartList.length !== 0 && data.cartList.every((item) => item.isChecked === 1)}},
10.全选和全不选功能
先绑定事件,获取选中状态,转换成0和1,调用接口将本地数据也更新
// 全选和全不选功能async selectAllStatus(event) {const { detail } = eventconst isChecked = detail ? 1 : 0//调用接口await reqCheckAllStatus(isChecked)if (res.code === 200) {// 第一种方法// this.showTipGetList()// 第二种方法// 对购物车列表进行深拷贝,对新数组进行遍历const newCartList = JSON.parse(JSON.stringify(this.data.cartList))newCartList.forEach((item) => (item.isChecked = isChecked))// 对cartList进行赋值,驱动视图更新this.setData({cartList: newCartList})}},