vue实现阶梯价格
Vue 实现阶梯价格功能
阶梯价格(Tiered Pricing)通常用于根据购买数量或金额的不同区间设置不同价格。以下是基于 Vue 的实现方案:
数据结构和配置
定义一个阶梯价格配置数组,包含区间和对应价格:
data() {
return {
tiers: [
{ min: 0, max: 10, price: 100 },
{ min: 11, max: 50, price: 90 },
{ min: 51, max: Infinity, price: 80 }
],
quantity: 1
}
}
计算当前价格
使用计算属性根据输入数量匹配对应价格区间:
computed: {
currentPrice() {
const { quantity } = this
const tier = this.tiers.find(t =>
quantity >= t.min && quantity <= t.max
)
return tier ? tier.price : 0
},
totalPrice() {
return this.quantity * this.currentPrice
}
}
模板渲染
在模板中显示阶梯价格表和实时计算结果:
<div>
<input v-model.number="quantity" type="number" min="1">
<table>
<tr v-for="(tier, index) in tiers" :key="index">
<td>{{ tier.min }}-{{ isFinite(tier.max) ? tier.max : '∞' }}</td>
<td>{{ tier.price }}</td>
</tr>
</table>
<p>单价: {{ currentPrice }}</p>
<p>总价: {{ totalPrice }}</p>
</div>
动态样式增强
为当前匹配的价格区间添加高亮样式:
methods: {
isActiveTier(tier) {
return this.quantity >= tier.min && this.quantity <= tier.max
}
}
<tr
v-for="(tier, index) in tiers"
:key="index"
:class="{ active: isActiveTier(tier) }"
>
完整组件示例
<template>
<div class="tiered-pricing">
<h3>数量</h3>
<input
v-model.number="quantity"
type="number"
min="1"
class="quantity-input"
>
<h3>价格阶梯</h3>
<table class="tiers-table">
<thead>
<tr>
<th>数量区间</th>
<th>单价</th>
</tr>
</thead>
<tbody>
<tr
v-for="(tier, index) in tiers"
:key="index"
:class="{ active: isActiveTier(tier) }"
>
<td>{{ tier.min }}-{{ isFinite(tier.max) ? tier.max : '∞' }}</td>
<td>¥{{ tier.price }}</td>
</tr>
</tbody>
</table>
<div class="price-summary">
<p>当前单价: ¥{{ currentPrice }}</p>
<p>总价: ¥{{ totalPrice }}</p>
</div>
</div>
</template>
<script>
export default {
data() {
return {
tiers: [
{ min: 0, max: 10, price: 100 },
{ min: 11, max: 50, price: 90 },
{ min: 51, max: Infinity, price: 80 }
],
quantity: 1
}
},
computed: {
currentPrice() {
const { quantity } = this
const tier = this.tiers.find(t =>
quantity >= t.min && quantity <= t.max
)
return tier ? tier.price : 0
},
totalPrice() {
return this.quantity * this.currentPrice
}
},
methods: {
isActiveTier(tier) {
return this.quantity >= tier.min && this.quantity <= tier.max
}
}
}
</script>
<style>
.tiered-pricing {
max-width: 500px;
margin: 0 auto;
}
.quantity-input {
padding: 8px;
width: 100%;
}
.tiers-table {
width: 100%;
border-collapse: collapse;
margin: 20px 0;
}
.tiers-table th,
.tiers-table td {
border: 1px solid #ddd;
padding: 8px;
text-align: left;
}
.tiers-table tr.active {
background-color: #f0f8ff;
font-weight: bold;
}
.price-summary {
margin-top: 20px;
font-size: 1.1em;
}
</style>
扩展功能
支持服务端获取阶梯配置:
async created() {
try {
const response = await axios.get('/api/pricing-tiers')
this.tiers = response.data
} catch (error) {
console.error('获取价格阶梯失败:', error)
}
}
添加价格校验:

watch: {
quantity(newVal) {
if (newVal < 1) {
this.quantity = 1
}
}
}



