电商app项目----vuex实现点击商品添加至购物车

 <!-- 底部商品导航 -->
 <detail-footer-bar class="footer_bar" @addCart="addCart"></detail-footer-bar>

addCart() 函数

    //1、点击商品添加到购物车
    addCart() {
        let product = {} //用来保存添加到购物车中的商品 需要展示的信息; 
        product.img = this.detailSwiper[0];   //用来保存一张商品的图片
        product.title = this.goodsInfo.title; //商品标题
        product.desc = this.goodsInfo.desc;   //商品描述
        product.price = this.goodsInfo.realPrice; //商品的价格
        product.iid = this.iid; //商品的id
        // product.count = 1;  //计算商品的数量,默认是1
    //2、将商品添加到购物车中
    this.$store.dispatch('addProduct',product);
    this.$toast.setDefaultOptions({ duration: 1000 });  //把默认的弹框时间设置为1秒;
    this.$toast("添加商品成功");
    },

vuex

  • store/index.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)   //1、安装插件

import mutations from './mutations.js' //导入mutations 对象
import actions from './actions.js'  // 导入actions 对象
export default new Vuex.Store({    //2、创建store对象
  state: {  cartList:[]  },    //商品的数组
  mutations,
  actions,
  modules: { }
})
  • /mutations.js
export default {
    //mutations 唯一的目的就是修改state中状态,  mutations 中的每个方法尽可能完成的事件比较单一 一点; 
    addCounter(state, obj) {  obj.count++ }, // //这两个事件分开写,就能更好的追踪 它们的变化
    addToCart(state, newObj) {
        newObj.isCheck = true;
        state.cartList.push(newObj)
    }
}
  • actions.js— 因为 addProduct 这个函数完成的是两个 任务 所以最好写在actions中;
export default {
    addProduct(context,obj) {
        let oldProduct = null;
        for(let item of context.state.cartList){   // 查找之前数组中是否有这个商品
            if(item.iid===obj.iid){ oldProduct = item; }
        }
        if(oldProduct){          //当商品已添加时    
            context.commit('addCounter',oldProduct)     // oldProduct.count += 1
        }else{           //当商品没有添加时,给oldProduct 添加一个记录商品件数的 属性  
            obj.count = 1;     
            context.commit("addToCart",obj)    // state.cartList.push(obj);
        }
    }
}


商品具体信息下的底部封装
<template>
    <div class="detail_footer_bar">
        <van-goods-action>
            <van-goods-action-icon icon="chat-o" text="客服" />
            <van-goods-action-icon icon="shop-o" text="店铺" info="" />
            <van-goods-action-icon icon="star-o" text="收藏" />
            <van-goods-action-button type="warning" text="加入购物车" @click="addToCart" />
            <van-goods-action-button type="danger" text="立即购买" />
        </van-goods-action>
    </div>
</template>
<script>
export default {
    name: "DetailFooterBar",
    methods:{
        addToCart() {  this.$emit('addCart')  }   // console.log("点击添加到购物车")
    }
};
</script>
  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值