同步徽標(biāo)
- 將購物車的數(shù)據(jù)用一個(gè)數(shù)據(jù)存儲起來壁袄,在car數(shù)組中,存儲一些商品的對象 媚媒,id:商品的id嗜逻,count:要購買的數(shù)量,price:商品的單價(jià)缭召,selected:false商品在 購物車中是否被選中
state:{
car:[]
},
- 拼接出一個(gè)要保存到store中car數(shù)組里的商品對象信息(直接在加入購物車按鈕綁定的方法中定義)
addToShopCar(){
this.ballFlag=!this.ballFlag
var goodsinfo={
id:this.id,
count:this.selectedCount,
price:this.goodsinfo.price,
selected:true
}
},
- 點(diǎn)擊加入購物車栈顷,把商品的信息保存到store的car上逆日,如果購物車中有這個(gè)對應(yīng)的商品了就只需要更新數(shù)量,如果沒有萄凤,則直接把商品數(shù)據(jù)push到car中
mutations:{
addToCar(state,goodsinfo){
var flag=false
state.car.some(item=>{
if(item.id==goodsinfo.id){
item.count+=parseInt(goodsinfo.count)
flag=true
return true
}
})
if(!flag){
state.car.push(goodsinfo)
}
}
},
- 調(diào)用store中的mutations來講商品加入購物車
this.$store.commit("addToCar",goodsinfo)
- 實(shí)現(xiàn)徽標(biāo)的自動(dòng)更新室抽,在getter中使用方法讓所有商品數(shù)量相加,并把它同步到頁面中
getter:{
getAllCount(state){
var c=0
state.car.forEach(item=>{
c+=item.count
})
return c
}
}
<span class="mui-badge" id="badge">{{$store.getters.getAllCount}}</span>
- 實(shí)現(xiàn)購物車的本地持久存儲靡努,當(dāng)更新car后坪圾,把car數(shù)組存儲到本地的localStorage中,在加入購物車方法中添加
localStorage.setItem('car',JSON.stringify(state.car))
- 從本地取出之前存儲的car數(shù)據(jù)惑朦,在main.js中操作
localStorage.getItem('car')||'[]'
繪制購物車頁面的商品列表
-
使用mui中的card樣式先簡略制作 商品卡片和結(jié)算價(jià)格兩部分
使用mint-ui中的switch組件設(shè)置一個(gè)勾選按鈕兽泄,用于勾選是否結(jié)算價(jià)格再設(shè)置一個(gè)數(shù)字選擇框用于購物車界面
<div class="goods-list">
<div class="mui-card">
<div class="mui-card-content">
<div class="mui-card-content-inner">
<mt-switch v-model="value"></mt-switch>
<img src="../../images/小米.jpg" height="728" width="446"/></div>
<div class="info">
<h1></h1>
<p>
<span class="price">$2199</span>
<numbox></numbox>
<a href="#">刪除</a>
</p>
</div>
</div>
</div>
</div>
<style scoped>
.shopcar-container{
background-color: #eee;
overflow: hidden;
}
.goods-list img{
width: 60px;
height: 60px;
}
h1{
font-size: 13px;
}
.price{
color: red;
font-weight: bold;
}
.mui-card-content-inner{
display: flex;
align-items: center;
}
.info{
display: flex;
flex-direction: column;
justify-content: space-between;
}
</style>