123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104 |
- import {
- removeProductFromCart,
- fetchCartProductCount,
- shoppingAddCart,
- updateProductCount,
- updateProductUnit
- } from '@/services/api/cart.js'
- const state = {
- kindCount: 0
- }
- const mutations = {
- SET_KIND_COUNT: (state, count) => {
- state.kindCount = count
- },
- // 设置购物车商品数量角标
- SET_TABBAR_BADGE: (state, num) => {
- console.log(num)
- if (num >= 100) {
- return uni.setTabBarBadge({ index: 2, text: '99+' })
- }
- if (num > 0) {
- return uni.setTabBarBadge({ index: 2, text: num.toString() })
- }
- uni.removeTabBarBadge({ index: 2 })
- },
- }
- const actions = {
- // 加入购物车
- async addToCart({ dispatch, rootGetters }, { skuId, productCount = 1, heUserId = 0 }) {
- if (!rootGetters.userId) {
- const pages = getCurrentPages()
- const page = pages[pages.length - 1]
- uni.setStorageSync('LOGIN_REDIRECT_URL', page.$page.fullPath)
- uni.redirectTo({ url: '/pages/authorize/login-custom' })
- return Promise.reject('用户未登录')
- }
- try {
- const res = await shoppingAddCart({ skuId, userId: rootGetters.userId, productCount, heUserId })
- dispatch('fetchCartKindCount')
- setTimeout(() => {
- uni.showToast({
- icon: 'success',
- title: '加入购物车成功',
- mask: true
- })
- }, 200)
- return res
- } catch (e) {
- return Promise.reject(e)
- }
- },
- // 获取购物车商品数量
- async fetchCartKindCount({ commit, rootGetters }) {
- try {
- const res = await fetchCartProductCount({ userId: rootGetters.userId })
- commit('SET_KIND_COUNT', res.data)
- commit('SET_TABBAR_BADGE', res.data)
- return res
- } catch (e) {
- return Promise.reject(e)
- }
- },
- // 从购物车移除
- async removeFromCart({ commit, dispatch }, cartIds = []) {
- try {
- const res = await removeProductFromCart({ cartIds: cartIds.join(',') })
- await dispatch('fetchCartKindCount')
- uni.showToast({ icon: 'success', title: '删除成功' })
- return res
- } catch (e) {
- return Promise.reject(e)
- }
- },
- // 加减购物车商品更新到后台
- async updateProductCount({ dispatch }, { cartId, productCount }) {
- try {
- return updateProductCount({ cartId, productCount })
- } catch (e) {
- return Promise.reject(e)
- }
- },
- // 购物车商品规格更新
- async updateProductUnit({ dispatch }, { cartId, newSkuId, productCount }) {
- try {
- return updateProductUnit({ newSkuId, cartId, count: productCount })
- } catch (e) {
- return Promise.reject(e)
- }
- }
- }
- export default {
- namespaced: true,
- state,
- mutations,
- actions
- }
|