Skip to content

实现 折扣/满减计算器 工具

分类:general | 标签:折扣、满减、到手价、计算 算到手价与立省金额,支持折扣叠加满减,适合大促比价

2.1 功能说明

算到手价与立省金额,支持折扣叠加满减,适合大促比价

2.1.1 使用指南

使用指导

输入原价、折扣与满减规则,快速算到手价与立省金额,适合大促凑单、比价。

说明

· 折扣填"几折":8.5 表示 85 折(即原价×0.85)。

· 满减:原价达到门槛才减;可与折扣叠加(先打折再满减)。

2.2 代码实现

2.2.1 组件结构

本工具是一个基于 Vue 3 <script setup> 语法的单文件组件(SFC),统一包裹在 ToolPageShell 组件内,由它提供页面标题、工具 ID、分类与「使用指南」插槽等通用外壳;核心业务逻辑(响应式状态、计算属性、事件处理函数)全部写在 <script setup> 中,输入/输出通过 el-inputel-button 等 Element Plus 组件与用户交互,所有数据均在浏览器本地处理,不会上传服务器。

2.2.2 核心逻辑概览

<script setup> 中定义的主要函数/方法:

  • num()
  • calc()
  • fmt()

2.2.3 关键实现代码

以下是该工具的完整 <script setup> 实现(核心代码)。模板(<template>)与样式(<style>)已省略。

vue
import { ref, computed } from 'vue'
import ToolPageShell from '@/components/ToolPageShell.vue'

const price = ref('199')
const discount = ref('8.5')
const threshold = ref('100')
const minus = ref('20')
const err = ref('')

function num(v) {
  const n = parseFloat(v)
  return isNaN(n) ? null : n
}

const priceNum = computed(() => num(price.value))
const discountNum = computed(() => num(discount.value))
const thresholdNum = computed(() => num(threshold.value) ?? 0)
const minusNum = computed(() => num(minus.value) ?? 0)

const priceAfterDiscount = computed(() => {
  if (priceNum.value === null || discountNum.value === null) return 0
  return priceNum.value * (discountNum.value / 10)
})
const meetsThreshold = computed(() => priceNum.value !== null && priceNum.value >= thresholdNum.value && thresholdNum.value > 0)
const finalPrice = computed(() => {
  let f = priceAfterDiscount.value
  if (meetsThreshold.value) f -= minusNum.value
  return Math.max(f, 0)
})
const saved = computed(() => (priceNum.value ?? 0) - finalPrice.value)
const strengthPct = computed(() => {
  if (!priceNum.value) return '0'
  return ((finalPrice.value / priceNum.value) * 10).toFixed(2)
})

function calc() {
  err.value = ''
  if (priceNum.value === null || priceNum.value < 0) { err.value = '原价必须是非负数字'; return }
  if (discountNum.value === null || discountNum.value <= 0 || discountNum.value > 10) { err.value = '折扣应在 0~10 之间(10 表示不打折)'; return }
  if (thresholdNum.value < 0 || minusNum.value < 0) { err.value = '满减金额不能为负'; return }
}

function fmt(n) { return (n || 0).toLocaleString('zh-CN', { maximumFractionDigits: 2 }) }
calc()

2.3 效果截图

折扣/满减计算器 效果截图

工具访问地址:https://www.i91tools.com/tools/discount-calculator