vue+vant+js實現購物車原理小demo(基礎版)


電商畢業設計里的一個購物車demo,拿vue+vant需要寫的核心計算代碼只有12行。效果圖:

 main.js:

Vue.use(Stepper);

 .vue文件

<template>
  <div class="box">
    <div class="flex-left tit">
      <span v-for="(i,inx) in tit" :key="inx" class="flex-around">{{i}}</span>
    </div>
    <div v-for="(item,s) in arr" :key="s" class="flex-around">
      <span>{{item.id}}</span>
      <span>{{item.name}}</span>
      <span>{{item.price}}</span>
      <van-stepper v-model="item.value" @change='change(item.value,s)'/>
      <input type="text" v-model='item.smallCount'></div>
    <p>共計:一共{{allValue}}件,共<input type="text" v-model="allCount"></p>
  </div>
</template>
<script>
export default {
    name: "push",
    data(){
        return{
           tit:['序號','名稱','單價','數量','小計'],
           arr:[],             //購物車
           allCount:0,         //價格總計
           allValue:0          //數量總計
        }
    },
    components:{
    },
    created:function(){
      this.jsfun()
    },
    methods:{
      jsfun(){
        let arr = []
        let obj1={
          id:1,
          name:'足球',
          price:10,
          value:1
        }
        let obj2={
          id:2,
          name:'籃球',
          price:20,
          value:1
        }
        let obj3={
          id:3,
          name:'水球',
          price:50,
          value:1
        }
        arr.push(obj1)
        arr.push(obj2)
        arr.push(obj3)
        arr.forEach(element => {
          element.smallCount = element.price*element.value
          this.allCount += element.price
        });
        console.log(arr)
        this.arr = arr                            //先在頁面加載時生成兩條購物車數據
        this.allValue = this.arr.length           //先在頁面加載時生成購物車內商品數量 
      },
      change(value,s){
         console.log(value,s)                     //value是當前購物車已選擇的值,s是當前購物車下標
         let allCount = 0
         let allValue = 0
         let arr = this.arr
         for(let i=0;i<arr.length;i++){
           arr[s].smallCount = arr[s].price*arr[s].value
           allCount += arr[i].smallCount
           allValue += arr[i].value
         }
         this.allCount = allCount
         this.allValue = allValue
      },
    } 
}
</script>
<style lang="less" scoped>
.box{
  font-size: 12px;
  background: white;
  padding: 10px 0;
  p{
   margin-top: 10px;
  }
}
.tit{
  margin-bottom: 10px;
  :nth-child(1){
    width: 7%;
  }
  :nth-child(2){
    width: 7%;
  }
  :nth-child(3){
    width: 9%;
  }
  :nth-child(4){
    width: 27%;
  }
  :nth-child(5){
    width: 44%;
  }
}
.van-stepper {
    font-size: 0;
    user-select: none;
    display: flex;
}
</style>

 

 


免責聲明!

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



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