電商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>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章