前端多规格选择方法

实现一个多规格选择功能的完整Vue组件需要考虑几个方面：数据模型、用户界面、事件处理以及与后端的数据交互。以下是一个简单的示例，展示如何在Vue组件中实现一个基本的多规格选择功能。

<template>
	<div class="product-sku">
		<div class="sku-option">
			<label>颜色:</label>
			<button v-for="color in colors" :key="color.id" :class="{ active: selectedColor === color.id }"
				@click="selectColor(color.id)">
				{{ color.name }}
			</button>
		</div>
		<div class="sku-option">
			<label>尺寸:</label>
			<button v-for="size in sizes" :key="size.id" :class="{ active: selectedSize === size.id }"
				@click="selectSize(size.id)">
				{{ size.name }}
			</button>
		</div>
		<div class="sku-result">
			<p>选择的规格: {{ selectedColorName }} - {{ selectedSizeName }}</p>
			<p v-if="selectedSku">价格: {{ selectedSku.price }}</p>
			<p v-if="selectedSku">库存: {{ selectedSku.stock  }}</p>
		</div>
	</div>
</template>

<script>
	export default {
		data() {
			return {
				colors: [{
						id: 1,
						name: '红色'
					},
					{
						id: 2,
						name: '蓝色'
					},
					// 更多颜色...
				],
				sizes: [{
						id: 1,
						name: 'S'
					},
					{
						id: 2,
						name: 'M'
					},
					{
						id: 3,
						name: 'L'
					},
					// 更多尺寸...
				],
				skus: [
					// 假设每个SKU包含颜色ID、尺寸ID、价格和库存
					{
						colorId: 1,
						sizeId: 1,
						price: 100,
						stock: 50,
						name: '红色-S'
					},
					// 更多SKU...
				],
				selectedColor: null,
				selectedSize: null,
				selectedColorName: '',
				selectedSizeName: '',
			};
		},
		computed: {
			selectedSku() {
				return this.skus.find(
					sku => sku.colorId == this.selectedColor && sku.sizeId == this.selectedSize
				);
			},
		},
		
		// function cartesianProduct(...arrays) {
		//   return arrays.reduce((accumulator, currentValue) => {
		//     return accumulator.flatMap(item1 =>
		//       currentValue.map(item2 => item1.concat(item2))
		//     );
		//   }, [[]]);
		// }
		
		// // 示例数组
		// const array1 = ['苹果', '香蕉'];
		// const array2 = ['大', '小'];
		// const array3 = ['甜', '酸'];
		
		// // 生成笛卡尔积
		// const product = cartesianProduct(array1, array2, array3);
		// console.log(product);
		
		
		
		methods: {
			selectColor(colorId) {
				this.selectedColor = colorId;
				this.selectedColorName = this.colors.find(color => color.id === colorId).name;
				this.updateSku();
			},
			selectSize(sizeId) {
				this.selectedSize = sizeId;
				this.selectedSizeName = this.sizes.find(size => size.id === sizeId).name;
				this.updateSku();
			},
			updateSku() {
				if (this.selectedColor && this.selectedSize) {
					const sku = this.selectedSku;
					if (sku) {
						console.log(`Selected SKU: ${sku.name}, Price: ${sku.price}, Stock: ${sku.stock}`);
					}
				}
			},
		},
	};
</script>




<style scoped>
	.sku-option button {
		margin: 5px;
		padding: 5px;
		border: 1px solid #ccc;
		border-radius: 5px;
		background-color: #f8f8f8;
		cursor: pointer;
	}

	.sku-option button.active {
		background-color: #42b983;
		color: white;
	}

	.sku-result {
		margin-top: 20px;
	}
</style>