vue实现多个商品对比
Vue 实现多个商品对比功能
实现多个商品对比功能需要处理商品选择、对比展示以及交互逻辑。以下是具体实现方案:
商品选择组件
创建商品选择组件,允许用户勾选需要对比的商品。可以使用复选框或按钮触发选择。

<template>
<div class="product-list">
<div v-for="product in products" :key="product.id" class="product-item">
<input type="checkbox" v-model="selectedProducts" :value="product.id">
<span>{{ product.name }}</span>
</div>
</div>
</template>
<script>
export default {
data() {
return {
products: [
{ id: 1, name: '商品A' },
{ id: 2, name: '商品B' },
{ id: 3, name: '商品C' }
],
selectedProducts: []
}
}
}
</script>
对比展示组件
创建对比表格组件,展示选中商品的各项参数对比。
<template>
<div v-if="selectedProducts.length > 1" class="comparison-table">
<table>
<thead>
<tr>
<th>参数</th>
<th v-for="product in productsToCompare" :key="product.id">
{{ product.name }}
</th>
</tr>
</thead>
<tbody>
<tr v-for="spec in specifications" :key="spec.name">
<td>{{ spec.name }}</td>
<td v-for="product in productsToCompare" :key="product.id">
{{ product.specs[spec.key] }}
</td>
</tr>
</tbody>
</table>
</div>
</template>
<script>
export default {
props: {
productsToCompare: {
type: Array,
required: true
}
},
data() {
return {
specifications: [
{ name: '价格', key: 'price' },
{ name: '重量', key: 'weight' },
{ name: '颜色', key: 'color' }
]
}
}
}
</script>
状态管理
对于复杂场景,建议使用 Vuex 管理对比商品状态。

// store.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
comparisonProducts: []
},
mutations: {
addToComparison(state, product) {
if (!state.comparisonProducts.some(p => p.id === product.id)) {
state.comparisonProducts.push(product)
}
},
removeFromComparison(state, productId) {
state.comparisonProducts = state.comparisonProducts.filter(
p => p.id !== productId
)
}
}
})
交互优化
添加最大选择限制和移除功能,提升用户体验。
<template>
<div>
<button @click="compareSelected" :disabled="selectedProducts.length < 2">
对比商品
</button>
<button
v-for="product in comparedProducts"
:key="product.id"
@click="removeProduct(product.id)"
>
移除 {{ product.name }}
</button>
</div>
</template>
响应式样式
为对比表格添加响应式样式,确保在不同设备上良好显示。
.comparison-table {
overflow-x: auto;
}
table {
width: 100%;
border-collapse: collapse;
}
th, td {
padding: 8px;
text-align: left;
border-bottom: 1px solid #ddd;
}
@media (max-width: 768px) {
.product-item {
display: flex;
align-items: center;
margin-bottom: 10px;
}
}
实现要点包括商品选择机制、对比数据展示、状态管理和响应式设计。可根据实际需求调整功能细节和界面样式。






