<!-- 底部商品導航 -->
<detail-footer-bar class="footer_bar" @addCart="addCart"></detail-footer-bar>
addCart() 函數
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;
this.$store.dispatch('addProduct',product);
this.$toast.setDefaultOptions({ duration: 1000 });
this.$toast("添加商品成功");
},
vuex
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
import mutations from './mutations.js'
import actions from './actions.js'
export default new Vuex.Store({
state: { cartList:[] },
mutations,
actions,
modules: { }
})
export default {
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)
}else{
obj.count = 1;
context.commit("addToCart",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') }
}
};
</script>