uniapp项目实战购物车界面
时间: 2023-11-18 12:03:35 浏览: 139
以下是uniapp项目实战购物车界面的步骤和代码示例:
1. 在store.js文件中定义购物车的状态和相关操作方法:
```javascript
const store = new Vuex.Store({
state: {
ShoppingCart: [] // 购物车商品列表
},
mutations: {
// 添加商品到购物车
addToCart(state, product) {
let item = state.ShoppingCart.find(item => item.id === product.id)
if (item) {
item.quantity++
item.total = item.quantity * item.price
} else {
state.ShoppingCart.push({
...product,
quantity: 1,
total: product.price
})
}
},
// 从购物车中删除商品
removeFromCart(state, product) {
let index = state.ShoppingCart.findIndex(item => item.id === product.id)
if (index !== -1) {
state.ShoppingCart.splice(index, 1)
}
},
// 清空购物车
clearCart(state) {
state.ShoppingCart = []
}
},
getters: {
// 计算购物车产品的总数量
total(state) {
let arr = state.ShoppingCart
var sum = 0
arr.map(item => {
sum += item.quantity
})
return sum
},
// 计算购物车的总价
price(state) {
let arr = state.ShoppingCart
var a = 0
arr.map(item => {
a += item.total
})
return a
}
}
})
```
2. 在商品列表页面中添加“加入购物车”按钮,并在点击事件中调用addToCart方法:
```html
<template>
<div>
<ul>
<li v-for="product in products" :key="product.id">
<span>{{ product.name }}</span>
<span>{{ product.price }}</span>
<button @click="addToCart(product)">加入购物车</button>
</li>
</ul>
</div>
</template>
<script>
import { mapMutations } from 'vuex'
export default {
data() {
return {
products: [
{ id: 1, name: '商品1', price: 10 },
{ id: 2, name: '商品2', price: 20 },
{ id: 3, name: '商品3', price: 30 }
]
}
},
methods: {
...mapMutations(['addToCart']),
}
}
</script>
```
3. 在购物车页面中展示购物车商品列表,并在每个商品后面添加“删除”按钮,并在点击事件中调用removeFromCart方法:
```html
<template>
<div>
<ul>
<li v-for="product in ShoppingCart" :key="product.id">
<span>{{ product.name }}</span>
<span>{{ product.price }}</span>
<span>{{ product.quantity }}</span>
<span>{{ product.total }}</span>
<button @click="removeFromCart(product)">删除</button>
</li>
</ul>
<div>总数量:{{ total }}</div>
<div>总价:{{ price }}</div>
</div>
</template>
<script>
import { mapState, mapMutations, mapGetters } from 'vuex'
export default {
computed: {
...mapState(['ShoppingCart']),
...mapGetters(['total', 'price'])
},
methods: {
...mapMutations(['removeFromCart'])
}
}
</script>
```
阅读全文