cart.js 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  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.removeTabBarBadge({ index: 2 })
  24. },
  25. }
  26. const actions = {
  27. // 加入购物车
  28. async addToCart({ dispatch, rootGetters }, { productId, 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({ productId, userId: rootGetters.userId, productCount, heUserId })
  38. uni.showToast({ icon: 'success', title: '加入购物车成功' })
  39. dispatch('fetchCartKindCount')
  40. return res
  41. } catch (e) {
  42. console.log(e)
  43. }
  44. },
  45. // 获取购物车商品数量
  46. async fetchCartKindCount({ commit, rootGetters }) {
  47. try {
  48. const res = await fetchCartProductCount({ userId: rootGetters.userId })
  49. commit('SET_KIND_COUNT', res.data)
  50. commit('SET_TABBAR_BADGE', res.data)
  51. return res
  52. } catch (e) {
  53. console.log(e)
  54. }
  55. },
  56. // 从购物车移除
  57. async removeFromCart({ commit, dispatch }, cartIds = []) {
  58. try {
  59. const res = await removeProductFromCart({ cartIds: cartIds.join(',') })
  60. await dispatch('fetchCartKindCount')
  61. uni.showToast({ icon: 'success', title: '删除成功' })
  62. return res
  63. } catch (e) {
  64. console.log(e)
  65. }
  66. },
  67. // 加减购物车商品更新到后台
  68. async updateProductCount({ dispatch }, { cartId, productCount }) {
  69. try {
  70. return updateProductCount({ cartId, productCount })
  71. } catch (e) {
  72. console.log(e)
  73. }
  74. }
  75. }
  76. export default {
  77. namespaced: true,
  78. state,
  79. mutations,
  80. actions
  81. }