cart.js 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  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. 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. export default {
  83. namespaced: true,
  84. state,
  85. mutations,
  86. actions
  87. }