vue sku 实现
Vue SKU 实现方法
在电商项目中,SKU(Stock Keeping Unit)是商品属性的组合选择功能。以下是基于 Vue 的实现方案:
数据结构设计
需要定义商品属性和 SKU 列表的数据结构:
data() {
return {
goods: {
specs: [
{ name: '颜色', values: ['红色', '蓝色'] },
{ name: '尺寸', values: ['S', 'M'] }
],
skus: [
{ specs: ['红色', 'S'], price: 100, stock: 10 },
{ specs: ['红色', 'M'], price: 110, stock: 5 }
]
},
selected: {}
}
}
选择逻辑实现
通过计算属性处理已选规格和可用规格:

computed: {
selectedSpecs() {
return Object.values(this.selected)
},
availableSpecs() {
const available = {}
this.goods.skus.forEach(sku => {
if (this.isSkuAvailable(sku.specs)) {
sku.specs.forEach((spec, index) => {
if (!available[index]) available[index] = new Set()
available[index].add(spec)
})
}
})
return available
}
},
methods: {
isSkuAvailable(specs) {
return this.selectedSpecs.every(
(selected, index) => !selected || specs[index] === selected
)
}
}
模板渲染
使用 v-for 渲染规格选择界面:
<div v-for="(spec, index) in goods.specs" :key="index">
<h3>{{ spec.name }}</h3>
<button
v-for="value in spec.values"
:key="value"
:disabled="!isSpecAvailable(index, value)"
@click="selectSpec(index, value)"
:class="{ active: selected[index] === value }"
>
{{ value }}
</button>
</div>
状态更新方法
处理规格选择逻辑:

methods: {
selectSpec(index, value) {
if (this.selected[index] === value) {
this.$delete(this.selected, index)
} else {
this.$set(this.selected, index, value)
}
},
isSpecAvailable(index, value) {
const tempSelected = { ...this.selected, [index]: value }
return this.goods.skus.some(sku => {
return sku.specs.every(
(spec, i) => !tempSelected[i] || spec === tempSelected[i]
)
})
}
}
完整 SKU 匹配
当所有规格选中时,显示对应 SKU 信息:
computed: {
currentSku() {
if (Object.keys(this.selected).length !== this.goods.specs.length) {
return null
}
return this.goods.skus.find(sku =>
sku.specs.every((spec, index) => spec === this.selected[index])
)
}
}
界面优化技巧
- 禁用不可选规格样式
button:disabled { opacity: 0.5; cursor: not-allowed; }
button.active { border-color: red; }
2. 添加库存提示
```html
<div v-if="currentSku">
价格:{{ currentSku.price }} 库存:{{ currentSku.stock }}
</div>
<div v-else>
请选择完整规格
</div>
通过以上方法可以实现基本的 Vue SKU 选择功能。实际项目中可能需要根据业务需求调整数据结构或交互逻辑。






