用vue 写一个多sku的案例
时间: 2023-06-30 18:06:37 浏览: 99
vue+element实现sku表格
好的,这里给您提供一个简单的多SKU的Vue案例。
首先,我们需要定义一个数据结构来存储SKU信息,这里我们使用一个数组来存储每个SKU的属性和对应的价格和库存:
```javascript
const skuList = [
{
id: 1,
name: '黑色,32GB',
price: 999,
stock: 100
},
{
id: 2,
name: '黑色,64GB',
price: 1099,
stock: 50
},
{
id: 3,
name: '白色,32GB',
price: 999,
stock: 80
},
{
id: 4,
name: '白色,64GB',
price: 1099,
stock: 30
}
]
```
接着,我们可以在Vue组件中使用v-for指令来渲染SKU列表:
```html
<div class="sku-list">
<div v-for="sku in skuList" :key="sku.id">
<input type="checkbox" v-model="selectedSkuIds" :value="sku.id"/>
<span>{{ sku.name }}</span>
<span>{{ sku.price }}</span>
<span>{{ sku.stock }}</span>
</div>
</div>
```
在上述代码中,我们使用了v-model指令来绑定一个选中SKU的数组,以便后续计算价格和库存。
接下来,我们需要在Vue组件中定义一个计算属性来根据选中的SKU计算出最终的价格和库存:
```javascript
computed: {
selectedSku() {
const selectedSkuList = this.skuList.filter(sku => this.selectedSkuIds.includes(sku.id))
const price = selectedSkuList.reduce((total, sku) => total + sku.price, 0)
const stock = Math.min(...selectedSkuList.map(sku => sku.stock))
return {
price,
stock
}
}
}
```
在上述代码中,我们使用了filter函数来过滤出选中的SKU,然后使用reduce函数计算出价格总和,使用Math.min函数计算出库存的最小值。
最后,我们可以在Vue组件中展示最终的价格和库存:
```html
<div class="selected-sku">
<span>已选SKU:{{ selectedSkuIds }}</span>
<span>价格:{{ selectedSku.price }}</span>
<span>库存:{{ selectedSku.stock }}</span>
</div>
```
完整的Vue多SKU示例代码如下:
```html
<template>
<div>
<div class="sku-list">
<div v-for="sku in skuList" :key="sku.id">
<input type="checkbox" v-model="selectedSkuIds" :value="sku.id"/>
<span>{{ sku.name }}</span>
<span>{{ sku.price }}</span>
<span>{{ sku.stock }}</span>
</div>
</div>
<div class="selected-sku">
<span>已选SKU:{{ selectedSkuIds }}</span>
<span>价格:{{ selectedSku.price }}</span>
<span>库存:{{ selectedSku.stock }}</span>
</div>
</div>
</template>
<script>
export default {
data() {
return {
skuList: [
{
id: 1,
name: '黑色,32GB',
price: 999,
stock: 100
},
{
id: 2,
name: '黑色,64GB',
price: 1099,
stock: 50
},
{
id: 3,
name: '白色,32GB',
price: 999,
stock: 80
},
{
id: 4,
name: '白色,64GB',
price: 1099,
stock: 30
}
],
selectedSkuIds: []
}
},
computed: {
selectedSku() {
const selectedSkuList = this.skuList.filter(sku => this.selectedSkuIds.includes(sku.id))
const price = selectedSkuList.reduce((total, sku) => total + sku.price, 0)
const stock = Math.min(...selectedSkuList.map(sku => sku.stock))
return {
price,
stock
}
}
}
}
</script>
```
阅读全文