cart.js 3.1 KB

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