vue实现计算商品sku笛卡尔积(干货)

在 Vue 中计算商品 SKU 的笛卡尔积,您可以按照以下步骤进行:

  1. 定义商品属性和属性值

在 Vue 组件中定义商品属性和属性值,可以使用对象或数组来表示:

// 商品属性
const attributes = {
  color: {
    name: '颜色',
    values: [
      { name: '红色', value: 'red' },
      { name: '蓝色', value: 'blue' },
      { name: '绿色', value: 'green' },
    ],
  },
  size: {
    name: '尺寸',
    values: [
      { name: 'S', value: 's' },
      { name: 'M', value: 'm' },
      { name: 'L', value: 'l' },
    ],
  },
};
  1. 计算属性值组合

使用嵌套循环来计算商品属性值的笛卡尔积,生成所有可能的属性值组合。

const attributeValues = Object.values(attributes).map(attr => attr.values);

const cartesianProduct = (...arrays) => arrays.reduce((acc, curr) =>
  acc.flatMap(a => curr.map(c => [...a, c]))
, [[]]);

const attributeCombinations = cartesianProduct(...attributeValues);

返回数据结构如图

  1. 生成 SKU 列表

使用属性值组合来生成 SKU 列表,给每个 SKU 分配一个唯一的编号。

const skuList = attributeCombinations.map((attributes, index) => ({
  id: index + 1,
  attributes: attributes.reduce((acc, attr, index) => {
    acc[Object.keys(attributes)[index]] = attr;
    return acc;
  }, {}),
  price: 0,
  stock: 0,
}));

在生成 SKU 列表时,您可以根据需要为每个 SKU 分配初始价格和库存数量,或者在后续的处理中动态计算。

  1. 显示商品属性和 SKU 列表

在 Vue 组件中,您可以使用 v-for 指令来显示商品属性和 SKU 列表。

<!-- 显示商品属性 -->
<div v-for="(attribute, attributeName) in attributes" :key="attributeName">
  <div>{{ attribute.name }}</div>
  <div>
    <div v-for="value in attribute.values" :key="value.value">
      <input type="radio" :id="`${attributeName}_${value.value}`"
        :name="attributeName" :value="value.value"
        v-model="selectedAttributes[attributeName]">
      <label :for="`${attributeName}_${value.value}`">{{ value.name }}</label>
    </div>
  </div>
</div>

<!-- 显示 SKU 列表 -->
<table>
  <thead>
    <tr>
      <th>ID</th>
      <th v-for="attribute in Object.keys(attributes)">{{ attributes[attribute].name }}</th>
      <th>价格</th>
      <th>库存</th>
    </tr>
  </thead>
  <tbody>
    <tr v-for="sku in skuList" :key="sku.id">
      <td>{{ sku.id }}</td>
      <td v-for="attribute in Object.keys(attributes)">{{ sku.attributes[attribute] }}</td>
      <td>{{ sku.price }}</td>
      <td>{{ sku.stock }}</td>
    </tr>
  </tbody>
</table>
  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值