vue 简单实现购物车:商品基础信息最终的 html 文件 + 商品计数器的组件处理,实现了购物车;
warning:
这篇文章距离上次修改已过201天,其中的内容可能已经有所变动。
<template>
<div id="app">
<h1>购物车示例</h1>
<div v-for="(item, index) in cart" :key="item.id">
<div>
<span>{{ item.name }}</span>
<span>{{ item.price }}</span>
<span>
<button @click="decrementItem(index)">-</button>
{{ item.quantity }}
<button @click="incrementItem(index)">+</button>
</span>
<span>{{ item.price * item.quantity }}</span>
</div>
</div>
</div>
</template>
<script>
export default {
name: 'App',
data() {
return {
cart: [
{ id: 1, name: '商品A', price: 100, quantity: 1 },
{ id: 2, name: '商品B', price: 200, quantity: 1 }
]
}
},
methods: {
incrementItem(index) {
this.cart[index].quantity++;
},
decrementItem(index) {
if (this.cart[index].quantity > 1) {
this.cart[index].quantity--;
}
}
}
}
</script>
这个简单的Vue应用展示了如何创建一个购物车组件,其中包含商品列表、商品单价、数量以及总价。用户可以通过点击按钮来增加或减少商品数量。这个例子教会了如何在Vue中处理简单的状态管理和用户事件。
评论已关闭