vue实现sku
Vue实现SKU(库存量单位)功能
SKU功能通常用于电商平台,用于管理商品的不同属性组合(如颜色、尺寸等)及其对应的库存和价格。以下是实现SKU功能的关键步骤和代码示例。
数据准备
定义商品属性和SKU组合的数据结构:
data() {
return {
attributes: [
{ name: '颜色', values: ['红色', '蓝色', '绿色'] },
{ name: '尺寸', values: ['S', 'M', 'L'] }
],
skus: [
{ id: 1, specs: ['红色', 'S'], price: 100, stock: 10 },
{ id: 2, specs: ['红色', 'M'], price: 110, stock: 5 },
{ id: 3, specs: ['蓝色', 'L'], price: 120, stock: 8 }
],
selectedSpecs: {}
}
}
属性选择交互
实现属性选择功能,通过v-for渲染属性选项:
<div v-for="attr in attributes" :key="attr.name">
<h3>{{ attr.name }}</h3>
<button
v-for="value in attr.values"
:key="value"
@click="selectSpec(attr.name, value)"
:class="{ active: selectedSpecs[attr.name] === value }"
>
{{ value }}
</button>
</div>
选择处理逻辑
在methods中实现选择逻辑:
methods: {
selectSpec(attrName, value) {
this.$set(this.selectedSpecs, attrName, value)
this.checkAvailability()
},
checkAvailability() {
// 检查当前选择的组合是否有库存
}
}
SKU匹配验证
实现SKU匹配验证功能:
checkAvailability() {
const selectedValues = Object.values(this.selectedSpecs)
if (selectedValues.length !== this.attributes.length) return
const matchedSku = this.skus.find(sku =>
sku.specs.every(spec => selectedValues.includes(spec))
)
if (matchedSku) {
console.log('匹配到的SKU:', matchedSku)
} else {
console.log('无匹配SKU')
}
}
完整示例组件
<template>
<div>
<div v-for="attr in attributes" :key="attr.name">
<h3>{{ attr.name }}</h3>
<button
v-for="value in attr.values"
:key="value"
@click="selectSpec(attr.name, value)"
:class="{ active: selectedSpecs[attr.name] === value }"
>
{{ value }}
</button>
</div>
<div v-if="currentSku">
<p>价格: {{ currentSku.price }}</p>
<p>库存: {{ currentSku.stock }}</p>
</div>
</div>
</template>
<script>
export default {
data() {
return {
attributes: [
{ name: '颜色', values: ['红色', '蓝色', '绿色'] },
{ name: '尺寸', values: ['S', 'M', 'L'] }
],
skus: [
{ id: 1, specs: ['红色', 'S'], price: 100, stock: 10 },
{ id: 2, specs: ['红色', 'M'], price: 110, stock: 5 },
{ id: 3, specs: ['蓝色', 'L'], price: 120, stock: 8 }
],
selectedSpecs: {},
currentSku: null
}
},
methods: {
selectSpec(attrName, value) {
this.$set(this.selectedSpecs, attrName, value)
this.checkAvailability()
},
checkAvailability() {
const selectedValues = Object.values(this.selectedSpecs)
if (selectedValues.length !== this.attributes.length) {
this.currentSku = null
return
}
this.currentSku = this.skus.find(sku =>
sku.specs.every(spec => selectedValues.includes(spec))
)
}
}
}
</script>
<style>
.active {
background-color: #42b983;
color: white;
}
</style>
高级功能扩展
对于更复杂的SKU场景,可以考虑以下扩展:
- 禁用无库存选项:在用户选择部分属性后,禁用与之冲突的选项
- 价格区间显示:当存在多个SKU时,显示最低和最高价格
- 图片切换:不同属性组合显示对应的商品图片
- 动态属性:根据API获取属性和SKU数据
性能优化
当属性较多或SKU数据量大时,可采用以下优化策略:
- 使用计算属性缓存计算结果
- 对SKU数据进行预处理,建立快速查找的数据结构
- 使用虚拟滚动处理大量选项的渲染
以上实现提供了Vue中SKU功能的核心逻辑,可根据实际需求进行调整和扩展。







