1. 程式人生 > 程式設計 >vue實現購物車案例

vue實現購物車案例

本文例項為大家分享了vue實現購物車的具體程式碼,供大家參考,具體內容如下

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width,initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>購物車案例</title>
  <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>
<style>
  *{
    padding: 0;
    margin:0
  }
  ul li{
    width: 1200px;
    display: flex;
    align-items: center;
    justify-content: center;
  }
  li div,.total{
    display: inline-block;
    width:200px;
    height: 50px;
    line-height: 50px;
    text-align: center;
  }
  button{
    width: 60px;
    height: 40px;
    text-align: center;
    line-height: 40px;
  }

</style>
<body>

  <div id="app">
    <ul>
      <goodsitem 
      v-for="item in goodslist" 
      :item="item" 
      :key="item.id"
      @onchange="(type)=>{handleCount(type,item)}"
      @ondelete="()=>{handleDelete(item.id)}">
      </goodsitem>
      <div class="total" style="padding-left: 113px">總價:{{total}}</div>
    </ul>
  </div>

</body>
<script>
  var computed={
    props:{
      count:{
         type:Number,require:true
      }
    },methods:{
      handleCount(type){
        this.$emit('onchange',type)
      }
    },template:`<div style="width:200px">
           <button @click="handleCount('sub')">-</button>
           <span>{{count}}</span>
           <button @click="handleCount('add')" >+</button>
         </div>
    
    `
    
  }
  var goodsitem={
    props:{
      item:{
        type:Object,type)
      },handleDelete(){
        this.$emit('ondelete')
      }
    },components:{
      computed
    },template:`<li>
         <div>{{item.goodsName}}</div>
         <div>{{item.price}}</div>
         <computed :count="item.count" @onchange="handleCount"></computed>
         <div>{{item.sum}}</div>
         <div><button @click="handleDelete">刪除</button></div>
         </li>
         `
  }

  var app=new Vue({
    el:"#app",data:{
      goodslist:[{
        id:1,goodsName:"小可愛",price:100,count:1,sum:100
      },{
        id:2,price:200,count:2,sum:400
      },{
        id:3,price:300,count:3,sum:900
      },{
        id:4,price:400,]
    },methods:{
      handleCount(type,item){
        if(type=='add'){
          item.count+=1
        }else{
          if(item.count==1){
            this.handleDelete(item.id) 
            return
            }
          item.count-=1
        }
        item.sum=item.count*item.price
      },handleDelete(id){
        return this.goodslist=this.goodslist.filter((item)=>{
          return id!=item.id
        })
      }
    },computed:{
      total(){
        return this.goodslist.reduce((total,item)=>{
           return total+=item.sum
        },0)
      }
    },components:{
      goodsitem
    }
  })
</script>
</html>

實現效果圖:

vue實現購物車案例

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。