用vue2写一个购物车
时间: 2023-07-16 09:16:39 浏览: 49
好的,以下是一个简单的购物车示例。
首先,我们需要一个商品列表和一个空购物车数组,以及一个计算总价的方法:
```javascript
data() {
return {
products: [
{ name: '商品A', price: 10 },
{ name: '商品B', price: 20 },
{ name: '商品C', price: 30 },
],
cart: [],
};
},
methods: {
addToCart(product) {
this.cart.push(product);
},
getTotalPrice() {
return this.cart.reduce((total, product) => total + product.price, 0);
},
},
```
然后,我们可以在页面上展示商品列表和购物车:
```html
<template>
<div>
<h2>商品列表</h2>
<ul>
<li v-for="product in products" :key="product.name">
{{ product.name }} - {{ product.price }}元
<button @click="addToCart(product)">加入购物车</button>
</li>
</ul>
<h2>购物车</h2>
<ul>
<li v-for="product in cart" :key="product.name">
{{ product.name }} - {{ product.price }}元
</li>
</ul>
<p>总价:{{ getTotalPrice() }}元</p>
</div>
</template>
```
最后,我们需要添加一些样式来让页面看起来更加美观:
```css
li {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 10px;
}
button {
margin-left: 10px;
}
```
这样,我们就完成了一个简单的购物车页面。完整的代码如下:
```html
<template>
<div>
<h2>商品列表</h2>
<ul>
<li v-for="product in products" :key="product.name">
{{ product.name }} - {{ product.price }}元
<button @click="addToCart(product)">加入购物车</button>
</li>
</ul>
<h2>购物车</h2>
<ul>
<li v-for="product in cart" :key="product.name">
{{ product.name }} - {{ product.price }}元
</li>
</ul>
<p>总价:{{ getTotalPrice() }}元</p>
</div>
</template>
<script>
export default {
data() {
return {
products: [
{ name: '商品A', price: 10 },
{ name: '商品B', price: 20 },
{ name: '商品C', price: 30 },
],
cart: [],
};
},
methods: {
addToCart(product) {
this.cart.push(product);
},
getTotalPrice() {
return this.cart.reduce((total, product) => total + product.price, 0);
},
},
};
</script>
<style>
li {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 10px;
}
button {
margin-left: 10px;
}
</style>
```
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)