vue实现多规格商品
Vue 实现多规格商品功能
数据结构设计
多规格商品通常需要处理 SKU(Stock Keeping Unit)和规格组合。基础数据结构可设计为:
data() {
return {
goods: {
specs: [
{ name: '颜色', values: ['红色', '蓝色'] },
{ name: '尺寸', values: ['S', 'M', 'L'] }
],
skus: [
{ specCombination: ['红色', 'S'], price: 100, stock: 10 },
{ specCombination: ['红色', 'M'], price: 110, stock: 5 }
]
},
selectedSpecs: {}
}
}
规格选择交互
使用动态渲染规格选项并处理选择状态:

methods: {
selectSpec(specName, value) {
this.$set(this.selectedSpecs, specName, value)
this.checkAvailability()
}
}
可用性校验
根据当前选择校验哪些规格可被继续选择:
computed: {
availableSpecs() {
const result = {}
this.goods.specs.forEach(spec => {
result[spec.name] = spec.values.filter(value => {
const tempSpecs = {...this.selectedSpecs, [spec.name]: value}
return this.hasValidSku(tempSpecs)
})
})
return result
}
}
SKU 匹配逻辑
检查当前规格组合是否存在对应 SKU:

methods: {
hasValidSku(specs) {
return this.goods.skus.some(sku => {
return this.goods.specs.every(spec => {
return !specs[spec.name] || sku.specCombination.includes(specs[spec.name])
})
})
}
}
价格与库存显示
显示当前选中规格对应的价格和库存:
computed: {
currentSku() {
return this.goods.skus.find(sku => {
return this.goods.specs.every(spec => {
return this.selectedSpecs[spec.name] === undefined ||
sku.specCombination.includes(this.selectedSpecs[spec.name])
})
})
}
}
界面渲染示例
<div v-for="spec in goods.specs" :key="spec.name">
<h3>{{ spec.name }}</h3>
<button
v-for="value in spec.values"
:key="value"
:disabled="!availableSpecs[spec.name]?.includes(value)"
@click="selectSpec(spec.name, value)"
:class="{ active: selectedSpecs[spec.name] === value }"
>
{{ value }}
</button>
</div>
<div v-if="currentSku">
<p>价格: {{ currentSku.price }}</p>
<p>库存: {{ currentSku.stock }}</p>
</div>
完整选择校验
在加入购物车或立即购买时验证是否选择了所有规格:
methods: {
validateSelection() {
return this.goods.specs.every(spec => this.selectedSpecs[spec.name])
}
}






