vuejs實現購物車功能


<body>
<h1 align="center">購物車實例</h1>
<div id="vm1">
<table align="center" width="800" border="1" cellpadding="0" cellspacing="0" >
<tr>
<th>序號</th>
<th>商品</th>
<th>單價</th>
<th>數量</th>
<th>小計</th>
<th>操作</th>
</tr>
<tr v-for="(product,index) in productsList">
<td>{{Number(index)+1}}</td>
<td>{{product.name}}</td>
<td class="money">{{product.price}}</td>

<td>
<button v-on:click="jian(index)">-</button>

<input type="text" v-model="product.num" v-on:input="change(index)">

<button v-on:click="add(index)">+</button>
</td>
<td class="money">{{product.price*product.num}}</td>
<td><button v-on:click="del(index)">移除購物車</button></td>
</tr>
</table>

<table align="center" width="800" border="1" cellpadding="5" cellspacing="0" style="margin-top: 60px;">
<tr>
<th>購買商品總數量</th>
<th>總價</th>
</tr>
<tr>
<td>{{ count2() }}</td>
<td class="money">{{ allMoney() }}</td>

</tr>
</table>
</div>

<script>
var vm1=new Vue({
el:'#vm1',
data:{
productsList:[
{id:'0',name:'iPhone 6 plus',price:'1000',num:1},
{id:'1',name:'電腦桌',price:'300',num:1},
{id:'2',name:'平板',price:'800',num:1}
]
},
methods:{
// 刪除
del:function(index){
if(confirm("您確定要刪除嗎?")){
this.productsList.splice(index,1);
}
},
// 增加
add:function(index){
if(this.productsList[index].num<100){
this.productsList[index].num++;
}
},
// 減少
jian:function(index){
if(this.productsList[index].num>1){
this.productsList[index].num--;
}
},
// 修改
change:function(index){
if(this.productsList[index].num>100){
this.productsList[index].num=100;
}else if(this.productsList[index].num<1){
this.productsList[index].num=1;
}
},
// 總數量
count2:function(){
var List=this.productsList;
var total=0;
for(var i=0;i<List.length;i++){
total+=parseInt(List[i].num);
}
return total;
},

// 總金額
allMoney:function(){
var List=this.productsList;
var totalMoney=0;
for(var i=0;i<List.length;i++){
totalMoney+=parseInt(List[i].num)*List[i].price;
}
return totalMoney;
}


}
});

 


</script>
</body>


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM