Coupon 优惠券 - Vant 4
🎫 Coupon 优惠券选择器
🎁 介绍
谁不喜欢优惠券呢?Coupon 优惠券组件就像一个贴心的购物助手,为你的应用带来完整的优惠券生态系统!🛍️
从优惠券的华丽展示到便捷的兑换功能,再到智能的选择机制,这个组件就像一个优惠券管家,让用户在享受折扣的同时感受到满满的仪式感。每一次使用优惠券,都像是在开启一个小小的惊喜盒子!✨
📦 引入
通过以下方式来全局注册组件,更多注册方式请参考组件注册。
js
import { createApp } from'vue';
import { CouponCell, CouponList } from'vant';
const app = createApp();
app.use(CouponCell);
app.use(CouponList);🎯 代码演示
🔧 基础用法 - 开启你的优惠券之旅
就像打开一个装满惊喜的宝盒!通过简单的配置,你就能为用户呈现一个功能完整、体验流畅的优惠券系统。从选择到兑换,每一步都充满了购物的乐趣。
html
js
import { ref } from'vue'; exportdefault { setup() { const coupon = { available: 1, condition: '无门槛\n最多优惠12元', reason: '', value: 150, name: '优惠券名称', startAt: 1489104000, endAt: 1514592000, valueDesc: '1.5', unitDesc: '元', }; const coupons = ref([coupon]); const showList = ref(false); const chosenCoupon = ref(-1); constonChange = (index) => { showList.value = false; chosenCoupon.value = index; }; constonExchange = (code) => { coupons.value.push(coupon); }; return { coupons, showList, onChange, onExchange, chosenCoupon, disabledCoupons: [coupon], }; }, };📖 API
CouponCell Props
| 参数 | 说明 | 类型 | 默认值 |
|---|---|---|---|
| title | 单元格标题 | string | 优惠券 |
| chosen-coupon | 当前选中优惠券的索引 | *number | number[]* |
| coupons | 可用优惠券列表 | Coupon[] | [] |
| editable | 能否切换优惠券 | boolean | true |
| border | 是否显示内边框 | boolean | true |
| currency | 货币符号 | string | ¥ |
CouponList Props
| 参数 | 说明 | 类型 | 默认值 |
|---|---|---|---|
| v-model:code | 当前输入的兑换码 | string | - |
| chosen-coupon | 当前选中优惠券的索引,支持多选(类型为 []) | *number | number[]* |
| coupons | 可用优惠券列表 | CouponInfo[] | [] |
| disabled-coupons | 不可用优惠券列表 | CouponInfo[] | [] |
| enabled-title | 可用优惠券列表标题 | string | 可使用优惠券 |
| disabled-title | 不可用优惠券列表标题 | string | 不可使用优惠券 |
| exchange-button-text | 兑换按钮文字 | string | 兑换 |
| exchange-button-loading | 是否显示兑换按钮加载动画 | boolean | false |
| exchange-button-disabled | 是否禁用兑换按钮 | boolean | false |
| exchange-min-length | 兑换码最小长度 | number | 1 |
| displayed-coupon-index | 滚动至特定优惠券位置 | number | - |
| show-close-button | 是否显示列表底部按钮 | boolean | true |
| close-button-text | 列表底部按钮文字 | string | 不使用优惠 |
| input-placeholder | 输入框文字提示 | string | 请输入优惠码 |
| show-exchange-bar | 是否展示兑换栏 | boolean | true |
| currency | 货币符号 | string | ¥ |
| empty-image | 列表为空时的占位图 | string | - |
| show-count | 是否展示可用 / 不可用数量 | boolean | true |
CouponList Events
| 事件名 | 说明 | 回调参数 |
|---|---|---|
| change | 优惠券切换回调 | index, 选中优惠券的索引 |
| exchange | 兑换优惠券回调 | code, 兑换码 |
CouponList Slots
| 名称 | 说明 |
|---|---|
| list-footer | 优惠券列表底部 |
| disabled-list-footer | 不可用优惠券列表底部 |
| list-button | 自定义底部按钮 |
CouponInfo 数据结构
| 键名 | 说明 | 类型 |
|---|---|---|
| id | 优惠券 id | string |
| name | 优惠券名称 | string |
| condition | 满减条件 | string |
| startAt | 卡有效开始时间 (时间戳, 单位秒) | number |
| endAt | 卡失效日期 (时间戳, 单位秒) | number |
| description | 描述信息,优惠券可用时展示 | string |
| reason | 不可用原因,优惠券不可用时展示 | string |
| value | 折扣券优惠金额,单位分 | number |
| valueDesc | 折扣券优惠金额文案 | string |
| unitDesc | 单位文案 | string |
类型定义
组件导出以下类型定义:
ts
importtype { CouponCellProps, CouponListProps, CouponInfo } from'vant';主题定制
样式变量
组件提供了下列 CSS 变量,可用于自定义样式,使用方法请参考 ConfigProvider 组件。
| 名称 | 默认值 | 描述 |
|---|---|---|
| --van-coupon-margin | 0 var(--van-padding-sm) var(--van-padding-sm) | - |
| --van-coupon-content-height | 84px | - |
| --van-coupon-content-padding | 14px 0 | - |
| --van-coupon-content-text-color | var(--van-text-color) | - |
| --van-coupon-background | var(--van-background-2) | - |
| --van-coupon-active-background | var(--van-active-color) | - |
| --van-coupon-radius | var(--van-radius-lg) | - |
| --van-coupon-shadow | 0 0 4px rgba(0, 0, 0, 0.1) | - |
| --van-coupon-head-width | 96px | - |
| --van-coupon-amount-color | var(--van-danger-color) | - |
| --van-coupon-amount-font-size | 30px | - |
| --van-coupon-currency-font-size | 40% | - |
| --van-coupon-name-font-size | var(--van-font-size-md) | - |
| --van-coupon-disabled-text-color | var(--van-text-color-2) | - |
| --van-coupon-description-padding | var(--van-padding-xs) var(--van-padding-md) | - |
| --van-coupon-description-border-color | var(--van-border-color) | - |
| --van-coupon-checkbox-color | var(--van-danger-color) | - |
| --van-coupon-list-background | var(--van-background) | - |
| --van-coupon-list-field-padding | 5px 0 5px var(--van-padding-md) | - |
| --van-coupon-list-exchange-button-height | 32px | - |
| --van-coupon-list-close-button-height | 40px | - |
| --van-coupon-list-empty-tip-color | var(--van-text-color-2) | - |
| --van-coupon-list-empty-tip-font-size | var(--van-font-size-md) | - |
| --van-coupon-list-empty-tip-line-height | var(--van-line-height-md) | - |
| --van-coupon-cell-selected-text-color | var(--van-text-color) | - |
🌟 最佳实践
优惠券数据管理
javascript
// 优惠券状态管理
const useCouponStore = () => {
const coupons = ref([]);
const selectedCoupon = ref(-1);
// 获取可用优惠券
const getAvailableCoupons = async (orderAmount) => {
const response = await fetch(`/api/coupons?amount=${orderAmount}`);
const data = await response.json();
return data.filter(coupon => {
// 检查使用条件
if (coupon.minAmount && orderAmount < coupon.minAmount) {
return false;
}
// 检查有效期
const now = Date.now() / 1000;
return coupon.startAt <= now && coupon.endAt >= now;
});
};
// 计算优惠金额
const calculateDiscount = (coupon, orderAmount) => {
if (coupon.type === 'percentage') {
return Math.min(orderAmount * coupon.value / 100, coupon.maxDiscount || Infinity);
}
return Math.min(coupon.value / 100, orderAmount);
};
return {
coupons,
selectedCoupon,
getAvailableCoupons,
calculateDiscount
};
};用户体验优化
javascript
// 智能推荐最优优惠券
const recommendBestCoupon = (coupons, orderAmount) => {
return coupons
.map(coupon => ({
...coupon,
discount: calculateDiscount(coupon, orderAmount)
}))
.sort((a, b) => b.discount - a.discount)[0];
};
// 优惠券到期提醒
const checkExpiringCoupons = (coupons) => {
const threeDaysLater = Date.now() / 1000 + 3 * 24 * 60 * 60;
return coupons.filter(coupon =>
coupon.endAt <= threeDaysLater && coupon.endAt > Date.now() / 1000
);
};
// 动画效果增强
const animateCouponSelection = (index) => {
const couponElement = document.querySelector(`[data-coupon-index="${index}"]`);
if (couponElement) {
couponElement.classList.add('coupon-selected-animation');
setTimeout(() => {
couponElement.classList.remove('coupon-selected-animation');
}, 300);
}
};💡 使用技巧
多种优惠券类型支持
javascript
// 优惠券类型枚举
const CouponType = {
FIXED: 'fixed', // 固定金额
PERCENTAGE: 'percentage', // 百分比折扣
SHIPPING: 'shipping', // 免运费
GIFT: 'gift' // 赠品
};
// 优惠券工厂函数
const createCoupon = (type, config) => {
const baseCoupon = {
id: generateId(),
name: config.name,
startAt: config.startAt,
endAt: config.endAt,
condition: config.condition || '无门槛',
type
};
switch (type) {
case CouponType.FIXED:
return {
...baseCoupon,
value: config.amount * 100, // 转换为分
valueDesc: config.amount.toString(),
unitDesc: '元'
};
case CouponType.PERCENTAGE:
return {
...baseCoupon,
value: config.percentage,
valueDesc: config.percentage.toString(),
unitDesc: '折',
maxDiscount: config.maxDiscount * 100
};
case CouponType.SHIPPING:
return {
...baseCoupon,
value: 0,
valueDesc: '免运费',
unitDesc: ''
};
default:
return baseCoupon;
}
};优惠券兑换码生成
javascript
// 兑换码生成器
const generateCouponCode = (length = 8) => {
const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
let result = '';
for (let i = 0; i < length; i++) {
result += chars.charAt(Math.floor(Math.random() * chars.length));
}
return result;
};
// 兑换码验证
const validateCouponCode = (code) => {
const rules = [
{ test: /^[A-Z0-9]+$/, message: '只能包含大写字母和数字' },
{ test: code => code.length >= 6, message: '长度至少6位' },
{ test: code => code.length <= 12, message: '长度不能超过12位' }
];
for (const rule of rules) {
const isValid = typeof rule.test === 'function'
? rule.test(code)
: rule.test.test(code);
if (!isValid) {
return { valid: false, message: rule.message };
}
}
return { valid: true };
};🔧 常见问题解决
优惠券叠加使用
javascript
// Q: 如何实现多张优惠券叠加使用?
// A: 实现优惠券组合逻辑
const applyCoupons = (coupons, orderAmount) => {
// 按优先级排序(固定金额 > 百分比 > 免运费)
const sortedCoupons = coupons.sort((a, b) => {
const priority = { fixed: 3, percentage: 2, shipping: 1 };
return priority[b.type] - priority[a.type];
});
let totalDiscount = 0;
let currentAmount = orderAmount;
for (const coupon of sortedCoupons) {
const discount = calculateDiscount(coupon, currentAmount);
totalDiscount += discount;
currentAmount -= discount;
// 防止过度优惠
if (currentAmount <= 0) {
currentAmount = 0.01; // 保留最小金额
break;
}
}
return {
totalDiscount,
finalAmount: Math.max(0.01, orderAmount - totalDiscount)
};
};优惠券状态同步
javascript
// Q: 如何处理优惠券在多个页面间的状态同步?
// A: 使用全局状态管理
// Pinia store
export const useCouponStore = defineStore('coupon', {
state: () => ({
availableCoupons: [],
selectedCoupons: [],
lastSyncTime: 0
}),
actions: {
async syncCoupons() {
const now = Date.now();
// 避免频繁同步
if (now - this.lastSyncTime < 30000) return;
try {
const response = await api.getCoupons();
this.availableCoupons = response.data;
this.lastSyncTime = now;
} catch (error) {
console.error('同步优惠券失败:', error);
}
},
selectCoupon(coupon) {
const index = this.selectedCoupons.findIndex(c => c.id === coupon.id);
if (index > -1) {
this.selectedCoupons.splice(index, 1);
} else {
this.selectedCoupons.push(coupon);
}
}
}
});优惠券过期处理
javascript
// 自动清理过期优惠券
const cleanExpiredCoupons = () => {
const now = Date.now() / 1000;
coupons.value = coupons.value.filter(coupon => {
if (coupon.endAt < now) {
// 发送过期通知
showNotify({
type: 'warning',
message: `优惠券"${coupon.name}"已过期`
});
return false;
}
return true;
});
};
// 定期检查
setInterval(cleanExpiredCoupons, 60000); // 每分钟检查一次🎨 设计灵感
创意优惠券样式
css
/* 撕边效果优惠券 */
.coupon-torn {
position: relative;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
border-radius: 8px;
}
.coupon-torn::before {
content: '';
position: absolute;
top: 50%;
right: -5px;
width: 10px;
height: 10px;
background: white;
border-radius: 50%;
transform: translateY(-50%);
box-shadow:
0 -15px 0 white,
0 15px 0 white,
0 -30px 0 white,
0 30px 0 white;
}
/* 金色VIP优惠券 */
.coupon-vip {
background: linear-gradient(45deg, #ffd700, #ffed4e);
border: 2px solid #ffa000;
box-shadow: 0 4px 20px rgba(255, 215, 0, 0.3);
position: relative;
overflow: hidden;
}
.coupon-vip::after {
content: '';
position: absolute;
top: -50%;
left: -50%;
width: 200%;
height: 200%;
background: linear-gradient(
45deg,
transparent,
rgba(255, 255, 255, 0.3),
transparent
);
animation: shine 3s infinite;
}
@keyframes shine {
0% { transform: translateX(-100%) translateY(-100%) rotate(45deg); }
100% { transform: translateX(100%) translateY(100%) rotate(45deg); }
}
/* 节日主题优惠券 */
.coupon-festival {
background:
radial-gradient(circle at 20% 80%, #ff6b6b 0%, transparent 50%),
radial-gradient(circle at 80% 20%, #4ecdc4 0%, transparent 50%),
radial-gradient(circle at 40% 40%, #45b7d1 0%, transparent 50%);
animation: festival-glow 2s ease-in-out infinite alternate;
}
@keyframes festival-glow {
from { box-shadow: 0 0 20px rgba(255, 107, 107, 0.5); }
to { box-shadow: 0 0 30px rgba(78, 205, 196, 0.5); }
}交互动画效果
css
/* 优惠券选中动画 */
.coupon-selected-animation {
animation: coupon-select 0.3s ease-out;
}
@keyframes coupon-select {
0% { transform: scale(1); }
50% { transform: scale(1.05); }
100% { transform: scale(1); }
}
/* 优惠券翻转效果 */
.coupon-flip {
transition: transform 0.6s;
transform-style: preserve-3d;
}
.coupon-flip:hover {
transform: rotateY(180deg);
}
.coupon-flip .front,
.coupon-flip .back {
position: absolute;
width: 100%;
height: 100%;
backface-visibility: hidden;
}
.coupon-flip .back {
transform: rotateY(180deg);
}🚀 高级功能扩展
智能优惠券推荐
vue
<template>
<div class="smart-coupon-recommender">
<div class="recommendation-header">
<h3>🎯 为您推荐</h3>
<span class="save-amount">预计节省 ¥{{ recommendedSavings }}</span>
</div>
<div class="recommended-coupons">
<div
v-for="coupon in recommendedCoupons"
:key="coupon.id"
class="recommended-coupon"
@click="selectRecommendedCoupon(coupon)"
>
<div class="coupon-badge">推荐</div>
<van-coupon-cell
:coupons="[coupon]"
:chosen-coupon="0"
/>
<div class="recommendation-reason">
{{ coupon.recommendReason }}
</div>
</div>
</div>
</div>
</template>
<script setup>
const recommendCoupons = (coupons, orderInfo) => {
return coupons
.map(coupon => ({
...coupon,
savings: calculateSavings(coupon, orderInfo),
recommendReason: getRecommendReason(coupon, orderInfo)
}))
.filter(coupon => coupon.savings > 0)
.sort((a, b) => b.savings - a.savings)
.slice(0, 3);
};
const getRecommendReason = (coupon, orderInfo) => {
if (coupon.type === 'shipping' && orderInfo.needsShipping) {
return '免运费,为您节省配送成本';
}
if (coupon.savings > orderInfo.amount * 0.1) {
return '超值优惠,节省超过10%';
}
return '适合当前订单,立即可用';
};
</script>📚 延伸阅读
技术文档
- Vue 3 组合式API - 现代Vue开发
- Pinia 状态管理 - 轻量级状态管理
- Web Storage API - 本地存储