Skip to content

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'; 
export default { 
  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); 
    const onChange = (index) => { showList.value = false; chosenCoupon.value = index; }; 
    const onExchange = (code) => { coupons.value.push(coupon); }; 
    return { coupons, showList, onChange, onExchange, chosenCoupon, disabledCoupons: [coupon], }; 
  }, 
};

📖 API

CouponCell Props

參數說明類型預設值
title單元格標題string優惠券
chosen-coupon當前選中優惠券的索引*numbernumber[]*
coupons可用優惠券列表Coupon[][]
editable能否切換優惠券booleantrue
border是否顯示內邊框booleantrue
currency貨幣符號string¥

CouponList Props

參數說明類型預設值
v-model:code當前輸入的兌換碼string-
chosen-coupon當前選中優惠券的索引,支援多選(類型為 []*numbernumber[]*
coupons可用優惠券列表CouponInfo[][]
disabled-coupons不可用優惠券列表CouponInfo[][]
enabled-title可用優惠券列表標題string可使用優惠券
disabled-title不可用優惠券列表標題string不可使用優惠券
exchange-button-text兌換按鈕文字string兌換
exchange-button-loading是否顯示兌換按鈕載入動畫booleanfalse
exchange-button-disabled是否禁用兌換按鈕booleanfalse
exchange-min-length兌換碼最小長度number1
displayed-coupon-index捲動至特定優惠券位置number-
show-close-button是否顯示列表底部按鈕booleantrue
close-button-text列表底部按鈕文字string不使用優惠
input-placeholder輸入框文字提示string請輸入優惠碼
show-exchange-bar是否展示兌換欄booleantrue
currency貨幣符號string¥
empty-image列表為空時的佔位圖string-
show-count是否展示可用 / 不可用數量booleantrue

CouponList Events

事件名說明回調參數
change優惠券切換回調index: number
exchange兌換優惠券回調code: string

CouponList Slots

名稱說明參數
list-header自訂列表頭部內容-
list-footer自訂列表底部內容-

CouponInfo 數據結構

鍵名說明類型
id優惠券 idnumber | string
name優惠券名稱string
condition滿減條件string
startAt卡有效開始時間 (時間戳, 單位秒)number
endAt卡失效日期 (時間戳, 單位秒)number
description描述資訊,優惠券可用時展示string
reason不可用原因,優惠券不可用時展示string
value折扣券優惠金額,單位分number
valueDesc折扣券優惠金額文案string
unitDesc單位文案string

類型定義

元件匯出以下類型定義:

ts
import type { CouponCellProps, CouponListProps, CouponInfo } from'vant';

主題定製

樣式變數

元件提供了下列 CSS 變數,可用於自訂樣式,使用方法請參考 ConfigProvider 元件

名稱預設值描述
--van-coupon-margin0 var(--van-padding-sm) var(--van-padding-sm)-
--van-coupon-content-height84px-
--van-coupon-content-padding14px 0-
--van-coupon-content-text-colorvar(--van-text-color)-
--van-coupon-backgroundvar(--van-background-2)-
--van-coupon-active-backgroundvar(--van-active-color)-
--van-coupon-radiusvar(--van-radius-lg)-
--van-coupon-shadow0 0 4px rgba(0, 0, 0, 0.1)-
--van-coupon-head-width96px-
--van-coupon-amount-colorvar(--van-danger-color)-
--van-coupon-amount-font-size30px-
--van-coupon-currency-font-size40%-
--van-coupon-name-font-sizevar(--van-font-size-md)-
--van-coupon-disabled-text-colorvar(--van-text-color-2)-
--van-coupon-description-paddingvar(--van-padding-xs) var(--van-padding-md)-
--van-coupon-description-border-colorvar(--van-border-color)-
--van-coupon-checkbox-colorvar(--van-danger-color)-
--van-coupon-list-backgroundvar(--van-background)-
--van-coupon-list-field-padding5px 0 5px var(--van-padding-md)-
--van-coupon-list-exchange-button-height32px-
--van-coupon-list-close-button-height40px-
--van-coupon-list-empty-tip-colorvar(--van-text-color-2)-
--van-coupon-list-empty-tip-font-sizevar(--van-font-size-md)-
--van-coupon-list-empty-tip-line-heightvar(--van-line-height-md)-
--van-coupon-cell-selected-text-colorvar(--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>

📚 延伸閱讀

技術文件

電商設計

相關元件

基於Vant構建的企業級移動端解決方案