当前位置:首页 > VUE

vue实现多规格商品

2026-02-24 06:53:33VUE

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: {}
  }
}

规格选择交互

使用动态渲染规格选项并处理选择状态:

vue实现多规格商品

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:

vue实现多规格商品

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])
  }
}

标签: 规格商品
分享给朋友:

相关文章

vue实现商品列表

vue实现商品列表

Vue实现商品列表的方法 使用Vue实现商品列表需要结合数据绑定、组件化和状态管理。以下是实现商品列表的几种常见方法: 基础数据绑定实现 在Vue组件中定义商品数据数组,使用v-for指令循环渲染商…

vue实现商品全选

vue实现商品全选

实现全选功能的基本思路 在Vue中实现商品全选功能,通常需要维护一个商品列表数据和一个选中状态数组。通过计算属性判断是否全选,通过方法控制全选或取消全选。 定义数据模型 data() {…

vue 实现商品列表

vue 实现商品列表

实现商品列表的基本结构 在Vue中实现商品列表,通常需要创建一个组件来展示商品数据。可以使用v-for指令循环渲染商品列表,并通过数据绑定动态显示商品信息。 <template> &…

vue实现双列商品卡片

vue实现双列商品卡片

Vue 实现双列商品卡片 使用 Vue 实现双列商品卡片可以通过 flex 布局或 grid 布局实现,以下是两种常见方法: 方法一:使用 Flex 布局 <template>…

vue实现商品的渲染

vue实现商品的渲染

实现商品列表渲染 使用Vue.js渲染商品列表需要结合数据绑定和循环指令。以下是一个基本实现方式: <template> <div class="product-list"&g…

vue实现商品尺寸规格

vue实现商品尺寸规格

实现商品尺寸规格的Vue方案 数据模型设计 商品规格通常包含多个维度(如颜色、尺寸),需设计嵌套数据结构: data() { return { specs: [ {…