cart.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. import {
  2. removeProductFromCart,
  3. fetchCartProductCount,
  4. shoppingAddCart,
  5. updateProductCount
  6. } from '@/services/api/cart.js'
  7. const state = {
  8. kindCount: 0
  9. }
  10. const mutations = {
  11. SET_KIND_COUNT: (state, count) => {
  12. state.kindCount = count
  13. },
  14. // 设置购物车商品数量角标
  15. SET_TABBAR_BADGE: (state, num) => {
  16. console.log(num)
  17. if (num >= 100) {
  18. return uni.setTabBarBadge({ index: 2, text: '99+' })
  19. }
  20. if (num > 0) {
  21. return uni.setTabBarBadge({ index: 2, text: num.toString() })
  22. }
  23. uni.setTabBarBadge({ index: 2, text: undefined })
  24. },
  25. }
  26. const actions = {
  27. // 加入购物车
  28. async addToCart({ dispatch, rootGetters }, { productId, productCount = 1, heUserId = 0 }) {
  29. try {
  30. const res = await shoppingAddCart({ productId, userId: rootGetters.userId, productCount, heUserId })
  31. uni.showToast({ icon: 'success', title: '加入购物车成功' })
  32. dispatch('fetchCartKindCount')
  33. return res
  34. } catch (e) {
  35. console.log(e)
  36. }
  37. },
  38. // 获取购物车商品数量
  39. async fetchCartKindCount({ commit, rootGetters }) {
  40. try {
  41. const res = await fetchCartProductCount({ userId: rootGetters.userId })
  42. commit('SET_KIND_COUNT', res.data)
  43. commit('SET_TABBAR_BADGE', res.data)
  44. return res
  45. } catch (e) {
  46. console.log(e)
  47. }
  48. },
  49. // 从购物车移除
  50. async removeFromCart({ commit, dispatch }, cartIds = []) {
  51. try {
  52. const res = await removeProductFromCart({ cartIds: cartIds.join(',') })
  53. await dispatch('fetchCartKindCount')
  54. uni.showToast({ icon: 'success', title: '删除成功' })
  55. return res
  56. } catch (e) {
  57. console.log(e)
  58. }
  59. },
  60. // 加减购物车商品更新到后台
  61. async updateProductCount({ dispatch }, { cartId, productCount }) {
  62. try {
  63. return updateProductCount({ cartId, productCount })
  64. } catch (e) {
  65. console.log(e)
  66. }
  67. }
  68. }
  69. export default {
  70. namespaced: true,
  71. state,
  72. mutations,
  73. actions
  74. }