vue 实现阶梯价格
Vue 实现阶梯价格功能
阶梯价格(Tiered Pricing)是一种根据购买数量或金额不同而设置不同价格区间的定价策略。在 Vue 中可以通过计算属性、表单绑定和条件渲染实现这一功能。
数据模型设计
定义阶梯价格的数据结构,通常是一个数组,每个元素包含区间和对应价格:
data() {
return {
tiers: [
{ min: 1, max: 10, price: 100 },
{ min: 11, max: 50, price: 90 },
{ min: 51, max: Infinity, price: 80 }
],
quantity: 1
}
}
价格计算逻辑
使用计算属性根据输入数量计算最终价格:

computed: {
totalPrice() {
const qty = this.quantity
const tier = this.tiers.find(t => qty >= t.min && qty <= t.max)
return qty * (tier ? tier.price : 0)
}
}
模板渲染
在模板中绑定输入框并显示计算结果:
<input v-model.number="quantity" type="number" min="1">
<div>单价: {{ currentTierPrice }}</div>
<div>总价: {{ totalPrice }}</div>
动态显示当前区间
添加计算属性显示当前适用的价格区间:

computed: {
currentTierPrice() {
const qty = this.quantity
const tier = this.tiers.find(t => qty >= t.min && qty <= t.max)
return tier ? tier.price : 0
}
}
完整组件示例
<template>
<div>
<h3>阶梯价格计算器</h3>
<label>
购买数量:
<input v-model.number="quantity" type="number" min="1">
</label>
<div v-if="currentTier">
<p>当前区间: {{ currentTier.min }} - {{ isInfinite(currentTier.max) ? '∞' : currentTier.max }} 件</p>
<p>单价: {{ currentTier.price }} 元</p>
<p>总价: {{ totalPrice }} 元</p>
</div>
</div>
</template>
<script>
export default {
data() {
return {
tiers: [
{ min: 1, max: 10, price: 100 },
{ min: 11, max: 50, price: 90 },
{ min: 51, max: Infinity, price: 80 }
],
quantity: 1
}
},
computed: {
currentTier() {
const qty = this.quantity
return this.tiers.find(t => qty >= t.min && qty <= t.max)
},
totalPrice() {
return this.quantity * (this.currentTier ? this.currentTier.price : 0)
}
},
methods: {
isInfinite(val) {
return val === Infinity
}
}
}
</script>
可视化价格区间表
可以增加一个表格展示所有价格区间:
<table>
<thead>
<tr>
<th>数量区间</th>
<th>单价</th>
</tr>
</thead>
<tbody>
<tr v-for="(tier, index) in tiers" :key="index">
<td>{{ tier.min }} - {{ isInfinite(tier.max) ? '∞' : tier.max }}</td>
<td>{{ tier.price }}</td>
</tr>
</tbody>
</table>
表单验证
添加数量输入的验证逻辑:
watch: {
quantity(newVal) {
if (newVal < 1) {
this.quantity = 1
}
}
}
动态阶梯价格配置
如果需要从后端API获取阶梯价格配置,可以使用axios等库:
created() {
axios.get('/api/price-tiers')
.then(response => {
this.tiers = response.data
})
}




