Browse Source

业务代码分离

yuwenjun1997 2 năm trước cách đây
mục cha
commit
34bedd2301
4 tập tin đã thay đổi với 186 bổ sung179 xóa
  1. 92 3
      common/goods.helper.js
  2. 24 32
      pages/tabBar/cart/cart.vue
  3. 25 36
      pages/views/cart/cart.vue
  4. 45 108
      pages/views/goods/goods-detail.vue

+ 92 - 3
common/goods.helper.js

@@ -1,4 +1,8 @@
-// 获取产品活动类型 (拼团 活动价 限时特价)
+import { fetchProductDetail } from '@/services/api/goods.js'
+import { fetchCouponListByProductId } from '@/services/api/coupon.js'
+import store from '@/store/index.js'
+
+/* 获取产品活动类型 (拼团 活动价 限时特价) */
 export function generateActivityType(productData) {
     const { collageStatus = 0, activeStatus = 0, discountStatus = 0 } = productData
     // 拼团价
@@ -17,7 +21,7 @@ export function generateActivityType(productData) {
     return 'normal' // 普通价
 }
 
-// 获取产品价格类型
+/* 获取产品价格类型 */
 export function generatePriceType(productData) {
     const { couponStatus = 0, collageStatus = 0, activeStatus = 0, discountStatus = 0, couponId } = productData
     // 拼团价
@@ -46,7 +50,7 @@ export function generatePriceType(productData) {
     }
 }
 
-// 导航栏按钮类别
+/* 导航栏按钮类别 */
 const navbarButtonGroup = {
     // 仅拼团
     group: {
@@ -79,6 +83,7 @@ const navbarButtonGroup = {
     }
 }
 
+/* 导航按钮文本 */
 export function generateNavbarButtonText(productData) {
     const { priceType } = productData
     const navbarButton = navbarButtonGroup[priceType]
@@ -104,3 +109,87 @@ export function generateNavbarButtonText(productData) {
     }
     return navbarButton
 }
+
+/* 生成导航菜单类型 */
+export function generateNavbarType(productInfo) {
+    const { couponStatus = 0, collageStatus = 0, activeStatus = 0, discountStatus = 0 } = productInfo
+    // 拼团价
+    if (collageStatus > 0) {
+        if (couponStatus === 1) {
+            return 'groupWithCoupon' // 拼团券后价
+        } else {
+            return 'group' // 拼团价
+        }
+    }
+    // 限时活动
+    else if (discountStatus > 0 || activeStatus > 0) {
+        if (couponStatus === 1) {
+            return 'activityWithCoupon' // 券后价
+        } else {
+            return 'normal' // 限时活动价格
+        }
+    }
+    // 无活动价
+    else {
+        if (couponStatus === 1) {
+            return 'normalWithCoupon' // 普通券后价
+        } else {
+            return 'normal' // 普通价
+        }
+    }
+}
+
+/* 处理商品信息 */
+function generateProductInfo(product) {
+    if (!product) return product
+    // 商品活动类型
+    product.activityType = generateActivityType(product)
+    product.priceType = generatePriceType(product)
+    product.skus = product.skus.map(sku => {
+        sku.activityType = generateActivityType(sku)
+        sku.priceType = generatePriceType(sku)
+        return sku
+    })
+    return product
+}
+
+/* 创建优惠券 */
+function generateCoupon(coupon) {
+    const obj = Object.assign({}, coupon)
+    // 添加标题
+    if (coupon.noThresholdFlag > 0) {
+        obj.couponTitle = `减¥${coupon.couponAmount}元`
+    } else {
+        obj.couponTitle = `满¥${coupon.touchPrice}元减¥${coupon.couponAmount}元`
+    }
+    // 添加优惠券状态
+    if (obj.useStatus === 0) {
+        obj.controlType = 'receive'
+    } else if (obj.useStatus === 1) {
+        obj.couponStatus = 'received'
+        obj.controlType = 'search'
+    }
+    return obj
+}
+
+/* 获取商品详情 */
+export async function fetchPorductInfo(productId) {
+    try {
+        const userId = store.getters.userId
+        const res = await fetchProductDetail({ productId, userId })
+        return generateProductInfo(res.data)
+    } catch (e) {
+        console.log(e)
+    }
+}
+
+/* 获取商品可用优惠券 */
+export async function fetchCouponListByProduct(productId) {
+    try {
+        const userId = store.getters.userId
+        const res = await fetchCouponListByProductId({ productId, userId })
+        return res.data.map(coupon => generateCoupon(coupon))
+    } catch (e) {
+        console.log(e)
+    }
+}

+ 24 - 32
pages/tabBar/cart/cart.vue

@@ -55,7 +55,10 @@
                 </view>
                 <!-- 失效商品 -->
                 <view class="supplier-area" v-if="expiredProducts.length > 0">
-                    <cm-cart-expired-area :expiredList="expiredProducts" @clear="onClearExp"></cm-cart-expired-area>
+                    <cm-cart-expired-area
+                        :expiredList="expiredProducts"
+                        @clear="removeExpModal = true"
+                    ></cm-cart-expired-area>
                 </view>
             </view>
 
@@ -109,15 +112,13 @@ import { fetchCouponListByProductIds } from '@/services/api/coupon.js'
 import { arrayUnique } from '@/common/utils.js'
 import { mapGetters, mapActions } from 'vuex'
 import CouponUtils from '@/common/couponUtils.js'
-import goodsDetailMixin from '@/mixins/goodsDetail.js'
-// 业务帮助函数
+import { fetchPorductInfo, fetchCouponListByProduct } from '@/common/goods.helper.js'
 import {
     totalAllCheckedProduct,
     computeTotalPrice,
     initFormatCouponList,
     makeCouponUseTip
 } from '@/common/business.helper.js'
-import { setTimeout } from 'timers'
 
 const resetData = () => ({
     isRequest: true,
@@ -157,7 +158,6 @@ const resetData = () => ({
 })
 
 export default {
-    mixins: [goodsDetailMixin],
     data() {
         return resetData()
     },
@@ -188,18 +188,22 @@ export default {
     },
 
     onPullDownRefresh() {
-        this.resetData()
-        this.fetchCartInfo()
+        this.initPage()
     },
 
     onShow() {
-        this.resetData()
-        this.fetchCartInfo()
-        this.fetchCartKindCount()
+        this.initPage()
     },
     methods: {
         ...mapActions('cart', ['removeFromCart', 'fetchCartKindCount']),
 
+        // 页面初始化
+        initPage() {
+            this.resetData()
+            this.fetchCartInfo()
+            this.fetchCartKindCount()
+        },
+
         // 初始化数据
         resetData() {
             const data = resetData()
@@ -207,15 +211,9 @@ export default {
                 this[key] = data[key]
             }
         },
-
-        // 清空失效商品
-        onClearExp() {
-            this.removeExpModal = true
-        },
-
+        
         // 确认清空失效商品
         async onConfirmRemoveExp(e) {
-            // removeProductFromCart
             if (!e.index) return
             try {
                 await this.removeFromCart(this.expiredProducts.map(product => product.cartId))
@@ -382,18 +380,14 @@ export default {
 
         // 商品规格修改
         async onUnitChange(e) {
-            try {
-                this.cartId = e.cartId
-                uni.showLoading({ title: '加载中...' })
-                this.productInfo = await this.fetchProductDetail(e.productId)
-                this.goodsCouponList = await this.fetchCouponListByProduct(e.productId)
-                setTimeout(() => {
-                    this.goodsBuyPopup = true
-                    uni.hideLoading()
-                }, 1000)
-            } catch (e) {
-                console.log(e)
-            }
+            this.cartId = e.cartId
+            uni.showLoading({ title: '加载中...' })
+            this.productInfo = await fetchPorductInfo(e.productId)
+            this.goodsCouponList = await fetchCouponListByProduct(e.productId)
+            setTimeout(() => {
+                this.goodsBuyPopup = true
+                uni.hideLoading()
+            }, 1000)
         },
 
         // 保存商品规格
@@ -406,9 +400,7 @@ export default {
                     productCount: e.count
                 })
                 this.$toast.success('规格修改成功')
-                this.resetData()
-                this.fetchCartInfo()
-                this.fetchCartKindCount()
+                this.initPage()
             } catch (e) {
                 console.log(e)
                 this.$toast.error('修改规格失败')

+ 25 - 36
pages/views/cart/cart.vue

@@ -63,7 +63,10 @@
                 </view>
                 <!-- 失效商品 -->
                 <view class="supplier-area" v-if="expiredProducts.length > 0">
-                    <cm-cart-expired-area :expiredList="expiredProducts" @clear="onClearExp"></cm-cart-expired-area>
+                    <cm-cart-expired-area
+                        :expiredList="expiredProducts"
+                        @clear="removeExpModal = true"
+                    ></cm-cart-expired-area>
                 </view>
                 <view style="height: 100rpx;"></view>
             </simple-safe-view>
@@ -116,7 +119,7 @@ import { fetchCouponListByProductIds } from '@/services/api/coupon.js'
 import { arrayUnique } from '@/common/utils.js'
 import { mapGetters, mapActions } from 'vuex'
 import CouponUtils from '@/common/couponUtils.js'
-import goodsDetailMixin from '@/mixins/goodsDetail.js'
+import { fetchPorductInfo, fetchCouponListByProduct } from '@/common/goods.helper.js'
 // 业务帮助函数
 import {
     totalAllCheckedProduct,
@@ -173,7 +176,6 @@ const resetData = () => ({
 })
 
 export default {
-    mixins: [goodsDetailMixin],
     data() {
         return resetData()
     },
@@ -190,32 +192,23 @@ export default {
                 discountedPrice: 0,
                 count: 0
             }
-
             if (this.currentCoupon) {
                 result.couponAmount = this.currentCoupon.couponAmount
                 result.discountedPrice = this.currentCoupon.couponAmount
             }
-
             result.allPrice = this.allPrice
-
             if (this.allPrice - result.discountedPrice > 0) {
                 result.finallyPrice = this.allPrice - result.couponAmount
             }
-
             result.count = this.checkedProductList.length
-
-            console.log(result)
-
             return result
         }
     },
     onPullDownRefresh() {
-        this.resetData()
-        this.fetchCartInfo()
+        this.initPage()
     },
     onShow() {
-        this.resetData()
-        this.fetchCartInfo()
+        this.initPage()
     },
     methods: {
         // 自定义导航触发事件
@@ -226,6 +219,12 @@ export default {
         },
         ...mapActions('cart', ['removeFromCart']),
 
+        // 页面初始化
+        initPage() {
+            this.resetData()
+            this.fetchCartInfo()
+        },
+
         // 初始化数据
         resetData() {
             const data = resetData()
@@ -234,19 +233,13 @@ export default {
             }
         },
 
-        // 清空失效商品
-        onClearExp() {
-            this.removeExpModal = true
-        },
-
         // 确认清空失效商品
         async onConfirmRemoveExp(e) {
             // removeProductFromCart
             if (!e.index) return
             try {
                 await this.removeFromCart(this.expiredProducts.map(product => product.cartId))
-                this.resetData()
-                this.fetchCartInfo()
+                this.initPage()
             } catch (e) {
                 console.log('删除失效商品失败')
             } finally {
@@ -273,6 +266,7 @@ export default {
         onCouponChange(index) {
             this.currentTab = index
         },
+        
         // 优惠券点击事件
         onCouponClick(coupon) {
             if (coupon.controlType === 'receive') {
@@ -281,6 +275,7 @@ export default {
                 this.visiable = false
             }
         },
+        
         // 设置couponTab数据
         makeCouponTabs() {
             return [
@@ -412,18 +407,14 @@ export default {
 
         // 商品规格修改
         async onUnitChange(e) {
-            try {
-                this.cartId = e.cartId
-                uni.showLoading({ title: '加载中...' })
-                this.productInfo = await this.fetchProductDetail(e.productId)
-                this.goodsCouponList = await this.fetchCouponListByProduct(e.productId)
-                setTimeout(() => {
-                    this.goodsBuyPopup = true
-                    uni.hideLoading()
-                }, 1000)
-            } catch (e) {
-                console.log(e)
-            }
+            this.cartId = e.cartId
+            uni.showLoading({ title: '加载中...' })
+            this.productInfo = await fetchProductDetail(e.productId)
+            this.goodsCouponList = await fetchCouponListByProduct(e.productId)
+            setTimeout(() => {
+                this.goodsBuyPopup = true
+                uni.hideLoading()
+            }, 1000)
         },
 
         // 保存商品规格
@@ -436,9 +427,7 @@ export default {
                     productCount: e.count
                 })
                 this.$toast.success('规格修改成功')
-                this.resetData()
-                this.fetchCartInfo()
-                this.fetchCartKindCount()
+                this.initPage()
             } catch (e) {
                 console.log(e)
                 this.$toast.error('修改规格失败')

+ 45 - 108
pages/views/goods/goods-detail.vue

@@ -94,7 +94,7 @@
             @open="$refs.receiveBuyPopup.close()"
             @close="$refs.receiveBuyPopup.open()"
         ></goods-activity-popup>
-       
+
         <!-- 分享弹窗 -->
         <cm-share-popup ref="sharePopup" :data="posterData" type="product"></cm-share-popup>
 
@@ -124,16 +124,18 @@
 </template>
 
 <script>
-// 配置
-import { generateNavbarButtonText } from './commons/helper.js'
-import { generateActivityType, generatePriceType } from '@/common/goods.helper.js'
 import uParse from '@/components/uni/uParse/src/wxParse'
 import { debounce } from '@/common/utils.js'
 import { shareDataResult } from '@/common/share.helper.js'
-import { fetchProductDetail } from '@/services/api/goods.js'
-import { fetchCouponListByProductId } from '@/services/api/coupon.js'
 import { queryStringify } from '@/common/utils.js'
 import { mapGetters, mapActions } from 'vuex'
+import {
+    generateNavbarButtonText,
+    fetchPorductInfo,
+    fetchCouponListByProduct,
+    generateNavbarType
+} from '@/common/goods.helper.js'
+
 export default {
     components: {
         uParse
@@ -182,7 +184,7 @@ export default {
         },
         // 商品导航类型
         navbarType() {
-            return this.generateNavbarType()
+            return generateNavbarType(this.productInfo)
         },
         // 当前商品默认可以使的优惠券
         couponTip() {
@@ -212,8 +214,7 @@ export default {
         this.jumpState = parseInt(options.jumpState)
     },
     onShow() {
-        this.autoplay = true
-        this.fetchProductDetail()
+        this.initPage()
     },
     onHide() {
         this.autoplay = false
@@ -227,22 +228,47 @@ export default {
             this.goodsBuyPopup = true
         },
 
+        async initPage() {
+            this.autoplay = true
+            // 获取商品详情
+            this.fetchProductDetail()
+            // 获取商品可用优惠券
+            this.couponList = await fetchCouponListByProduct(this.productId)
+        },
+
+        // 获取商品详情
+        async fetchProductDetail() {
+            this.productInfo = await fetchPorductInfo(this.productId)
+            this.isRequest = false
+            this.productInfo.heUserId = this.jumpState === 1 ? 0 : this.userId
+            this.initNavbarButton()
+        },
+
         // 商品提交
         onSubmit(detail) {
+            // 用户未登录
+            if (!this.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' })
+                this.goodsBuyPopup = false
+                return
+            }
+
+            // 加入购物车
             if (detail.type === 'cart') {
                 this.addToCart({
                     skuId: detail.sku.skuId,
                     productCount: detail.count,
                     heUserId: this.productInfo.heUserId
                 })
-            } else if (detail.type === 'buy') {
-                if (!this.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
-                }
+                this.goodsBuyPopup = false
+                return
+            }
+
+            // 立即购买
+            if (detail.type === 'buy') {
                 const submitData = {
                     productId: detail.sku.productId, // 产品id
                     skuId: detail.sku.skuId, // sku id
@@ -255,8 +281,9 @@ export default {
                 }
                 uni.setStorageSync('COMMIT_PRODUCT_INFO', submitData)
                 this.$router.navigateTo('order/order-create?type=product')
+                this.goodsBuyPopup = false
+                return
             }
-            this.goodsBuyPopup = false
         },
 
         // 优惠券点击事件
@@ -366,96 +393,6 @@ export default {
                     this.currentTab = index
                 }
             })
-        },
-
-        // 获取商品详情
-        async fetchProductDetail() {
-            try {
-                const res = await fetchProductDetail({ productId: this.productId, userId: this.userId })
-                this.isRequest = false
-                this.productInfo.heUserId = this.jumpState === 1 ? 0 : this.userId
-                this.productInfo = this.generateProductInfo(res.data)
-                this.initNavbarButton()
-                this.fetchCouponList()
-            } catch (e) {
-                console.log(e)
-                console.log('获取商品详情失败')
-            }
-        },
-
-        // 生成导航菜单类型
-        generateNavbarType() {
-            const { couponStatus = 0, collageStatus = 0, activeStatus = 0, discountStatus = 0 } = this.productInfo
-
-            // 拼团价
-            if (collageStatus > 0) {
-                if (couponStatus === 1) {
-                    return 'groupWithCoupon' // 拼团券后价
-                } else {
-                    return 'group' // 拼团价
-                }
-            }
-            // 限时活动
-            else if (discountStatus > 0 || activeStatus > 0) {
-                if (couponStatus === 1) {
-                    return 'activityWithCoupon' // 券后价
-                } else {
-                    return 'normal' // 限时活动价格
-                }
-            }
-            // 无活动价
-            else {
-                if (couponStatus === 1) {
-                    return 'normalWithCoupon' // 普通券后价
-                } else {
-                    return 'normal' // 普通价
-                }
-            }
-        },
-
-        // 创建优惠券
-        generateCoupon(coupon) {
-            const obj = Object.assign({}, coupon)
-            // 添加标题
-            if (coupon.noThresholdFlag > 0) {
-                obj.couponTitle = `减¥${coupon.couponAmount}元`
-            } else {
-                obj.couponTitle = `满¥${coupon.touchPrice}元减¥${coupon.couponAmount}元`
-            }
-            // 添加优惠券状态
-            if (obj.useStatus === 0) {
-                obj.controlType = 'receive'
-            } else if (obj.useStatus === 1) {
-                obj.couponStatus = 'received'
-                obj.controlType = 'search'
-            }
-            return obj
-        },
-
-        // 获取商品可用优惠券
-        async fetchCouponList() {
-            try {
-                const res = await fetchCouponListByProductId({ productId: this.productId, userId: this.userId })
-                this.couponList = res.data.map(coupon => this.generateCoupon(coupon))
-            } catch (e) {
-                //TODO handle the exception
-                console.log(e)
-                console.log('获取优惠券列表失败')
-            }
-        },
-
-        // 处理商品信息
-        generateProductInfo(product) {
-            if (!product) return product
-            // 商品活动类型
-            product.activityType = generateActivityType(product)
-            product.priceType = generatePriceType(product)
-            product.skus = product.skus.map(sku => {
-                sku.activityType = generateActivityType(sku)
-                sku.priceType = generatePriceType(sku)
-                return sku
-            })
-            return product
         }
     }
 }