1.添加购物车到组件:
- 添加了
添加购物车按钮,然后添加addProduct(item),将产品item作为参数传递进去。 - 用
mapActions来触发store中cart模块中的actions中的addProduct函数
<template>
<div>
<h2>我是商铺组件啊</h2>
<ul>
<li v-for="(item) in products" :key="item.id">
{{item.title}}-{{item.price | currency}} <br>
<button @click="addProduct(item)">添加购物车</button>
</li>
</ul>
</div>
</template>
<script>
import {
mapState,
mapActions
} from 'vuex';
export default {
//组件名字用来注册全库组件时候使用
name: "ProductList",
created() {
//发送请求
this.$store.dispatch("products/getAllProducts")
},
computed: {
...mapState('products', ['products']),
},
mounted() {},
// 😆这里用mapActions来触发store中cart模块中的actions中的addProduct函数
methods: {
...mapActions("cart", ["addProduct"])
}
};
</script>
<style lang="scss" scoped>
</style>
2.store中的购物车模块-cart.js
🌵接下来看下 store 中的 modules 的 cart.js 模块
- 这里的
cartList主要存储了商品的id和数量quantity
export default {
namespaced:true,
state:{
count:0,
cartList:[{id:1,quantity:1}]
},
mutations:{
//🌵之前没有添加过该商品,那就push到数组中去
addProductToCart(state,{id,quantity}){
// state.cartList = product;
state.cartList.push({id,quantity});
},
//🌵之前以后添加过该商品,就find找到后,对其数量+1
incrementCartQuantity(state,{id}){
const curItem = state.cartList.find(item=>item.id===id);
curItem.quantity++;
}
},
actions:{
addProduct({commit,state},product){
if(product.inventory > 0)//如果有库存
{
const cartItem = state.cartList.find(item=>{
return item.id === product.id
});
console.log("我是数组find方法的返回值",cartItem);
//购物车中没有数据,新添加到购物车
if(!cartItem)
{
commit("addProductToCart",{id:product.id,quantity:1});
}else{
//购物车中已有数据
commit("incrementCartQuantity",{id:product.id})
}
}
}
}
}
🤔那么如何拿到产品的价格等信息呢?