优惠券的使用功能优化

This commit is contained in:
xiaowang
2026-02-28 17:09:45 +08:00
parent e74dc3faa4
commit c95394260d
9 changed files with 631 additions and 49 deletions
+43 -2
View File
@@ -1,7 +1,7 @@
<template>
<el-config-provider>
<div class="app-container">
<BottomNav v-if="!isHiddenNav" />
<BottomNav v-if="!isHiddenNav" ref="bottomNavRef" />
<div class="page-content" :class="{ 'no-nav-padding': isHiddenNav }">
<router-view v-slot="{ Component }">
<transition name="page-fade" mode="out-in">
@@ -14,11 +14,13 @@
</template>
<script setup lang="ts">
import { computed } from 'vue'
import { computed, ref, provide, watch } from 'vue'
import { useRoute } from 'vue-router'
import BottomNav from './components/BottomNav.vue'
import { cartApi } from './api/cart'
const route = useRoute()
const bottomNavRef = ref<InstanceType<typeof BottomNav> | null>(null)
const isHiddenNav = computed(() => {
// 检查当前路由及其所有父路由是否有 hideNav: true
@@ -27,6 +29,45 @@ const isHiddenNav = computed(() => {
console.log('isHiddenNav:', result, 'matched routes:', route.matched)
return result
})
// 全局购物车数量状态
const cartCount = ref(0)
// 加载购物车数量
const loadCartCount = async () => {
try {
const data = await cartApi.getCartList()
// 计算购物车商品总数
const totalQuantity = data.reduce((sum: number, item: any) => sum + (item.quantity || 0), 0)
console.log('购物车商品总数:', totalQuantity)
// 更新全局购物车数量状态
cartCount.value = totalQuantity
} catch (error) {
console.error('获取购物车数量失败:', error)
}
}
// 提供更新购物车数量的方法
const updateCartCount = async () => {
await loadCartCount()
}
provide('updateCartCount', updateCartCount)
provide('cartCount', cartCount)
// 监听路由变化,更新购物车数量
watch(() => route.path, async () => {
// 检查当前是否是后台页面,如果是则不加载购物车数据
const isAdminPage = route.matched.some(r => r.meta.isAdmin)
if (!isAdminPage) {
await loadCartCount()
}
})
// 页面加载时获取购物车数量
loadCartCount()
// 每30秒自动更新一次购物车数量
setInterval(loadCartCount, 30000)
</script>
<style>
+3
View File
@@ -57,5 +57,8 @@ export const userApi = {
},
getUserByAccount: (account: string) => {
return api.get<UserVO>(`/user/get/account/${account}`)
},
listUsersByType: (type: number) => {
return api.get<UserVO[]>(`/user/list/type/${type}`)
}
}
+17 -12
View File
@@ -45,29 +45,28 @@
</template>
<script setup lang="ts">
import { computed, ref, onMounted } from 'vue'
import { computed, inject, onMounted, ref } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { HomeOutlined, ShoppingOutlined, ShoppingCartOutlined, UserOutlined } from '@ant-design/icons-vue'
import { cartApi } from '../api/cart'
import { message } from 'ant-design-vue'
const router = useRouter()
const route = useRoute()
// 购物车商品数量
const cartCount = ref(0)
// 注入全局购物车数量状态
const cartCount = inject('cartCount', ref(0))
// 注入更新购物车数量的方法
const updateCartCount = inject<() => Promise<void>>('updateCartCount', async () => {})
// 是否有未读通知
const hasNotification = ref(true)
const hasNotification = computed(() => true)
// 加载购物车数量
const loadCartCount = async () => {
try {
const data = await cartApi.getCartList()
cartCount.value = data.reduce((sum: number, item: any) => sum + item.quantity, 0)
} catch (error) {
console.error('获取购物车数量失败:', error)
}
// 这里我们不需要做任何事情,因为全局状态会自动更新
// 但我们仍然需要这个方法,因为 App.vue 会调用它
console.log('BottomNav loadCartCount called')
}
// 页面加载时获取购物车数量
@@ -75,10 +74,16 @@ onMounted(() => {
// 检查当前是否是后台页面,如果是则不加载购物车数据
const isAdminPage = window.location.pathname.startsWith('/admin')
if (!isAdminPage) {
loadCartCount()
// 调用全局更新方法
updateCartCount()
}
})
// 提供一个方法让其他组件调用更新购物车数量
defineExpose({
loadCartCount
})
// 根据当前路由判断激活的导航项
const currentRoute = computed(() => {
const path = route.path
+54 -12
View File
@@ -130,16 +130,41 @@
v-model:visible="showCouponModal"
title="选择优惠券"
width="90%"
@ok="confirmCouponSelection"
@cancel="cancelCouponSelection"
>
<div class="coupon-modal-content">
<a-empty v-if="availableCoupons.length === 0" description="暂无可用优惠券" />
<div v-else class="coupon-list">
<!-- 取消选择选项 -->
<a-card
class="modal-coupon-card"
:class="{ active: !selectedCoupon }"
@click="selectedCoupon = null"
>
<div class="coupon-content">
<div class="coupon-value">
不使用
</div>
<div class="coupon-info">
<div class="coupon-name">不使用优惠券</div>
<div class="coupon-condition">
直接结算
</div>
<div class="coupon-select" v-if="!selectedCoupon">
<CheckCircleOutlined />
</div>
</div>
</div>
</a-card>
<a-divider />
<!-- 优惠券列表 -->
<a-card
v-for="coupon in availableCoupons"
:key="coupon.id"
class="modal-coupon-card"
:class="{ active: selectedCoupon && selectedCoupon.id === coupon.id }"
@click="selectCoupon(coupon)"
@click="selectedCoupon = coupon"
>
<div class="coupon-content">
<div class="coupon-value">
@@ -193,7 +218,7 @@
</template>
<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue'
import { ref, computed, onMounted, watch, inject } from 'vue'
import { useRouter } from 'vue-router'
import {
LeftOutlined,
@@ -206,6 +231,11 @@ import { cartApi } from '../api/cart'
import { orderApi } from '../api/order'
import { fileApi } from '../api/index'
import { couponApi, type UserCoupon } from '../api/coupon'
import { userApi } from '../api/user'
// 注入更新购物车数量的方法
const updateCartCount = inject<() => Promise<void>>('updateCartCount', async () => {})
interface CartItem {
id: number
@@ -387,6 +417,8 @@ const handleDecreaseQuantity = async (item: CartItem) => {
await cartApi.updateCartQuantity({ productId: item.productId, quantity: item.quantity })
// 重新加载可用优惠券
await loadAvailableCoupons()
// 更新购物车数量
await updateCartCount()
} catch (error) {
message.error('更新数量失败')
item.quantity++
@@ -402,6 +434,8 @@ const handleIncreaseQuantity = async (item: CartItem) => {
await cartApi.updateCartQuantity({ productId: item.productId, quantity: item.quantity })
// 重新加载可用优惠券
await loadAvailableCoupons()
// 更新购物车数量
await updateCartCount()
} catch (error) {
message.error('更新数量失败')
item.quantity--
@@ -419,6 +453,8 @@ const handleDeleteItem = async (item: CartItem) => {
message.success('商品已删除')
// 重新加载可用优惠券
await loadAvailableCoupons()
// 更新购物车数量
await updateCartCount()
}
} catch (error) {
message.error('删除商品失败')
@@ -430,9 +466,13 @@ const handleBrowseProducts = () => {
router.push('/products')
}
// 选择优惠券
const selectCoupon = (coupon: UserCoupon) => {
selectedCoupon.value = coupon
// 确认优惠券选择
const confirmCouponSelection = () => {
showCouponModal.value = false
}
// 取消优惠券选择
const cancelCouponSelection = () => {
showCouponModal.value = false
}
@@ -444,15 +484,15 @@ const availableArtists = ref<{id: number, name: string}[]>([])
// 加载可用美甲师
const loadAvailableArtists = async () => {
try {
// 这里需要根据商品ID获取可用的美甲师
// 暂时使用模拟数据
availableArtists.value = [
{ id: 1, name: '美甲师1' },
{ id: 2, name: '美甲师2' },
{ id: 3, name: '美甲师3' }
]
// 获取美甲师列表(用户类型为3)
const artists = await userApi.listUsersByType(3)
availableArtists.value = artists.map(artist => ({
id: artist.id,
name: artist.nickname
}))
} catch (error) {
console.error('获取美甲师列表失败:', error)
availableArtists.value = []
}
}
@@ -485,6 +525,8 @@ const selectArtistAndCheckout = async () => {
})
message.success('订单创建成功')
showArtistModal.value = false
// 更新购物车数量(因为订单创建后购物车会被清空)
await updateCartCount()
router.push('/profile')
} catch (error) {
message.error('创建订单失败')
+286
View File
@@ -0,0 +1,286 @@
<template>
<div class="mobile-container">
<header class="header">
<a-button type="text" class="back-btn" @click="router.back()">
<LeftOutlined />
</a-button>
<h1>我的优惠券</h1>
<div class="placeholder"></div>
</header>
<div class="coupon-section">
<a-card :bordered="false" class="filter-card">
<a-segmented
v-model:value="activeFilter"
:options="filterOptions"
class="filter-segmented"
/>
</a-card>
<a-card v-if="loading" :bordered="false" class="content-card">
<a-skeleton :paragraph="{ rows: 3 }" />
</a-card>
<a-card v-else-if="coupons.length === 0" :bordered="false" class="content-card">
<a-empty description="暂无优惠券">
<a-button type="primary">去领取</a-button>
</a-empty>
</a-card>
<div v-else class="coupon-list">
<a-card
v-for="coupon in filteredCoupons"
:key="coupon.id"
class="coupon-card"
:class="{ 'expired': coupon.status === 3 }"
>
<div class="coupon-content">
<div class="coupon-value">
{{ coupon.couponType === 1 ? `${coupon.discountValue}折` : `¥${coupon.reduceAmount}` }}
</div>
<div class="coupon-info">
<div class="coupon-name">{{ coupon.couponName }}</div>
<div class="coupon-condition" v-if="coupon.couponType === 2">
满{{ coupon.minAmount }}元可用
</div>
<div class="coupon-time">
{{ formatDate(coupon.startTime) }} 至 {{ formatDate(coupon.endTime) }}
</div>
<div :class="['coupon-status', getStatusClass(coupon.status)]">
{{ coupon.statusName }}
</div>
</div>
</div>
</a-card>
</div>
</div>
</div>
</template>
<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { LeftOutlined } from '@ant-design/icons-vue'
import { message } from 'ant-design-vue'
import { couponApi } from '@/api/coupon'
const router = useRouter()
const loading = ref(false)
const coupons = ref<any[]>([])
const activeFilter = ref('all')
const filterOptions = [
{ label: '全部', value: 'all' },
{ label: '未使用', value: 'available' },
{ label: '已使用', value: 'used' },
{ label: '已过期', value: 'expired' }
]
const filteredCoupons = computed(() => {
if (activeFilter.value === 'all') {
return coupons.value
} else if (activeFilter.value === 'available') {
return coupons.value.filter(coupon => coupon.status === 1)
} else if (activeFilter.value === 'used') {
return coupons.value.filter(coupon => coupon.status === 2)
} else if (activeFilter.value === 'expired') {
return coupons.value.filter(coupon => coupon.status === 3)
}
return coupons.value
})
const loadCoupons = async () => {
loading.value = true
try {
const data = await couponApi.listUserCoupons()
coupons.value = data
} catch (error) {
console.error('获取优惠券列表失败:', error)
message.error('获取优惠券列表失败')
} finally {
loading.value = false
}
}
const getStatusClass = (status: number) => {
switch (status) {
case 1:
return 'available'
case 2:
return 'used'
case 3:
return 'expired'
default:
return ''
}
}
const formatDate = (dateString: string) => {
if (!dateString) return ''
const date = new Date(dateString)
return date.toLocaleDateString('zh-CN', {
year: 'numeric',
month: '2-digit',
day: '2-digit'
})
}
onMounted(() => {
loadCoupons()
})
</script>
<style scoped>
.mobile-container {
padding-top: 60px;
min-height: 100vh;
background: #f5f5f5;
}
.header {
position: fixed;
top: 0;
left: 0;
right: 0;
z-index: 100;
display: flex;
justify-content: space-between;
align-items: center;
padding: 10px 15px;
background: white;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}
.header h1 {
font-size: 18px;
font-weight: bold;
margin: 0;
color: #1a1a2e;
}
.back-btn {
width: 40px;
height: 40px;
display: flex;
align-items: center;
justify-content: center;
color: #1a1a2e;
}
.placeholder {
width: 40px;
}
.coupon-section {
padding: 15px;
}
.filter-card {
border-radius: 12px;
margin-bottom: 15px;
box-shadow: 0 4px 20px rgba(0, 0, 0, 0.05);
}
.filter-segmented {
width: 100%;
}
.content-card {
border-radius: 12px;
box-shadow: 0 4px 20px rgba(0, 0, 0, 0.05);
padding: 40px 20px;
}
.coupon-list {
display: flex;
flex-direction: column;
gap: 15px;
}
.coupon-card {
border-radius: 12px;
overflow: hidden;
background: linear-gradient(135deg, #f5f7ff 0%, #e8ecff 100%);
transition: all 0.3s ease;
}
.coupon-card:hover {
transform: translateY(-2px);
box-shadow: 0 6px 20px rgba(102, 126, 234, 0.15);
}
.coupon-card.expired {
opacity: 0.6;
background: linear-gradient(135deg, #f5f5f5 0%, #e8e8e8 100%);
}
.coupon-content {
display: flex;
align-items: center;
gap: 20px;
padding: 20px;
}
.coupon-value {
font-size: 24px;
font-weight: 700;
color: #667eea;
padding: 20px;
background: rgba(102, 126, 234, 0.1);
border-radius: 8px;
min-width: 100px;
text-align: center;
}
.coupon-card.expired .coupon-value {
color: #8b8b9a;
background: rgba(139, 139, 154, 0.1);
}
.coupon-info {
flex: 1;
display: flex;
flex-direction: column;
gap: 8px;
}
.coupon-name {
font-size: 16px;
font-weight: 600;
color: #1a1a2e;
}
.coupon-condition {
font-size: 12px;
color: #667eea;
}
.coupon-time {
font-size: 12px;
color: #8b8b9a;
}
.coupon-status {
font-size: 12px;
font-weight: 600;
padding: 2px 8px;
border-radius: 8px;
align-self: flex-start;
}
.coupon-status.available {
background: #f6ffed;
color: #52c41a;
}
.coupon-status.used {
background: #f5f5f5;
color: #8b8b9a;
}
.coupon-status.expired {
background: #fff1f0;
color: #ff4d4f;
}
</style>
+8 -1
View File
@@ -91,7 +91,7 @@
</template>
<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ref, onMounted, inject } from 'vue'
import { ArrowLeft, Star, Clock, Collection, ShoppingCart, Right } from '@element-plus/icons-vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
@@ -99,6 +99,9 @@ import { productApi, type ProductVO } from '@/api/product'
import { fileApi } from '@/api/index'
import { cartApi } from '@/api/cart'
// 注入更新购物车数量的方法
const updateCartCount = inject<() => Promise<void>>('updateCartCount', async () => {})
const router = useRouter()
const route = useRoute()
@@ -201,6 +204,8 @@ const handleAddToCart = async () => {
console.log('开始调用cartApi.addToCart')
await cartApi.addToCart({ productId: product.value.id, quantity: 1 })
console.log('调用cartApi.addToCart成功')
// 实时更新购物车角标数字
await updateCartCount()
ElMessage.success(`已将 ${product.value.title} 添加到购物车`)
} catch (error) {
console.error('添加到购物车失败:', error)
@@ -216,6 +221,8 @@ const handleBuyNow = async () => {
console.log('开始调用cartApi.addToCart')
await cartApi.addToCart({ productId: product.value.id, quantity: 1 })
console.log('调用cartApi.addToCart成功')
// 实时更新购物车角标数字
await updateCartCount()
// 跳转到购物车页面
console.log('开始跳转到购物车页面')
router.push('/cart')