一进来,默认是全选中状态,点击全选按钮后,变成全部不选中,商品列表展示可以滚动,可以任意勾选购物车列表商品是否选中购买。
从详情页将商品添加到购物车
1.给“加入购物车”添加点击事件,发送一个事件,因为是在子组件中监听。
在DetaiBottomBar.vue 中
<div class="cart" @click="addToCart">加入购物车</div>
methods: {
addToCart(){
this.$emit('addCart')
}
},
2.在详情页中监听点击,先获取商品的信息,这些信息要展示在购物车页面中;
在Detail.vue中
<detail-bottom-bar @addCart="addToCart"/>
addToCart(){
// 1.获取购物车需要展示的信息
const product={
}
product.image=this.topImages[0]
product.title=this.goods.title
product.desc=this.goods.desc
product.cartPrice=this.goods.cartPrice
product.iid=this.iid
}
** 3.将商品添加进购物车,在详情页将商品添加到某个位置,在购物车界面将信息进行展示,用到vuex管理购物车数据
从详情页将商品添加到store中
** 0.安装vuex npm install vuex --save
** 1.在文件夹store中新建一个文件,导入vue,vuex,安装插件,创建store对象,挂载到Vue实例上,在main.js中导入store
** 2.定义一个数组变量cartList在其中存放商品,修改任何state中的状态都要通过mutations。
在index.js中
const store = new Vuex.Store({
state:{
cartList: []
},
mutations:{
addCart(state,payload){
state.cartList.push(payload);
}
}
});
在Detail.vue中
addToCart(){
// 2.将商品添加到购物车
//这样做不好,修改vuex中的数据要通过mutations
//this.$store.cartList.push(product);
this.$store.commit('addCart',product)
}
此时应该做一个判断,如果添加的是同一个商品的话,cartList的长度不应该变化,而是变化数量。
用iid来判断。将一个商品添加进购物车,需要根据iid来判断它是不是在原来的cartList里面,如果是,则把该商品数量加1,如果不是,则添加进cartList里面。
mutations:{
addCart(state,payload){
let oldProduct=null;
for(let item of state.cartList){
if(item.iid===payload.iid){
oldProduct=item;
}
}
// 判断oldProduct
if(oldProduct){
oldProduct.count+=1;
}else{
payload.count=1;
state.cartList.push(payload);
}
}
},
对vuex进行重构
mutations唯一的目的就是修改state中状态。
mutations中的每个方法尽可能完成的事情比较单一。
现在addCart里面即进行了添加一个新的商品,又进行了一个新添加商品的数量增加,不好区分到底进行的是什么事情的时候,有判断逻辑的操作放到actions里面。
mutations:{
addCounter(state,payload){
payload.count++;
},
addCart(state,payload){
state.cartList.push(payload