vue+vant-stepper+js实现购物车原理小demo

电商毕业设计里的一个购物车demo,效果图:

 .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){                              //绑定的方法不建议使用plus()和minus(),冗余且在计算allCount出现了问题
         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>

猜你喜欢

转载自www.cnblogs.com/wd163/p/12964442.html