cart.js 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. import {
  2. removeProductFromCart,
  3. fetchCartProductCount,
  4. shoppingAddCart,
  5. updateProductCount,
  6. updateProductUnit
  7. } from '@/services/api/cart.js'
  8. const state = {
  9. kindCount: 0
  10. }
  11. const mutations = {
  12. SET_KIND_COUNT: (state, count) => {
  13. state.kindCount = count
  14. },
  15. // 设置购物车商品数量角标
  16. SET_TABBAR_BADGE: (state, num) => {
  17. console.log(num)
  18. if (num >= 100) {
  19. return uni.setTabBarBadge({ index: 2, text: '99+' })
  20. }
  21. if (num > 0) {
  22. return uni.setTabBarBadge({ index: 2, text: num.toString() })
  23. }
  24. uni.removeTabBarBadge({ index: 2 })
  25. },
  26. }
  27. const actions = {
  28. // 加入购物车
  29. async addToCart({ dispatch, rootGetters }, { skuId, productCount = 1, heUserId = 0 }) {
  30. if (!rootGetters.userId) {
  31. const pages = getCurrentPages()
  32. const page = pages[pages.length - 1]
  33. uni.setStorageSync('LOGIN_REDIRECT_URL', page.$page.fullPath)
  34. uni.redirectTo({ url: '/pages/authorize/login-custom' })
  35. return Promise.reject('用户未登录')
  36. }
  37. try {
  38. const res = await shoppingAddCart({ skuId, userId: rootGetters.userId, productCount, heUserId })
  39. dispatch('fetchCartKindCount')
  40. setTimeout(() => {
  41. uni.showToast({
  42. icon: 'success',
  43. title: '加入购物车成功',
  44. mask: true
  45. })
  46. }, 200)
  47. return res
  48. } catch (e) {
  49. return Promise.reject(e)
  50. }
  51. },
  52. // 获取购物车商品数量
  53. async fetchCartKindCount({ commit, rootGetters }) {
  54. try {
  55. const res = await fetchCartProductCount({ userId: rootGetters.userId })
  56. commit('SET_KIND_COUNT', res.data)
  57. commit('SET_TABBAR_BADGE', res.data)
  58. return res
  59. } catch (e) {
  60. return Promise.reject(e)
  61. }
  62. },
  63. // 从购物车移除
  64. async removeFromCart({ commit, dispatch }, cartIds = []) {
  65. try {
  66. const res = await removeProductFromCart({ cartIds: cartIds.join(',') })
  67. await dispatch('fetchCartKindCount')
  68. uni.showToast({ icon: 'success', title: '删除成功' })
  69. return res
  70. } catch (e) {
  71. return Promise.reject(e)
  72. }
  73. },
  74. // 加减购物车商品更新到后台
  75. async updateProductCount({ dispatch }, { cartId, productCount }) {
  76. try {
  77. return updateProductCount({ cartId, productCount })
  78. } catch (e) {
  79. return Promise.reject(e)
  80. }
  81. },
  82. // 购物车商品规格更新
  83. async updateProductUnit({ dispatch }, { cartId, newSkuId, productCount }) {
  84. try {
  85. return updateProductUnit({ newSkuId, cartId, count: productCount })
  86. } catch (e) {
  87. return Promise.reject(e)
  88. }
  89. }
  90. }
  91. export default {
  92. namespaced: true,
  93. state,
  94. mutations,
  95. actions
  96. }